[c++] Define a struct inside a class in C++

Can someone give me an example about how to define a new type of struct in a class in C++.

Thanks.

This question is related to c++ class struct

The answer is


declare class & nested struct probably in some header file

class C {
    // struct will be private without `public:` keyword
    struct S {
        // members will be public without `private:` keyword
        int sa;
        void func();
    };
    void func(S s);
};

if you want to separate the implementation/definition, maybe in some CPP file

void C::func(S s) {
    // implementation here
}
void C::S::func() { // <= note that you need the `full path` to the function
    // implementation here
}

if you want to inline the implementation, other answers will do fine.


Something like:

class Tree {

 struct node {
   int data;
   node *llink;
   node *rlink;
 };
 .....
 .....
 .....
};

Something like this:

class Class {
    // visibility will default to private unless you specify it
    struct Struct {
        //specify members here;
    };
};

The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.

The syntax for this is as follows:

class Container {

    ...

    struct Inner; // Declare, but not define, the struct.

    ...

};

struct Container::Inner {
   /* Define the struct here. */
};

You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.


Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.

As an example I am adding a simple Trie class.

class Trie {
private:
    struct node{
        node* alp[26];
        bool isend;
    };
    node* root;
    node* createNode(){
        node* newnode=new node();
        for(int i=0; i<26; i++){
            newnode->alp[i]=nullptr;
        }
        newnode->isend=false;
        return newnode;
    }
public:
    /** Initialize your data structure here. */
    Trie() {
        root=createNode();
    }

    /** Inserts a word into the trie. */
    void insert(string word) {
        node* head=root;
        for(int i=0; i<word.length(); i++){
            if(head->alp[int(word[i]-'a')]==nullptr){
                node* newnode=createNode();
                head->alp[int(word[i]-'a')]=newnode;
            }
            head=head->alp[int(word[i]-'a')];
        }
        head->isend=true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        node* head=root;
        for(int i=0; i<word.length(); i++){
            if(head->alp[int(word[i]-'a')]==nullptr){
                return false;
            }
            head=head->alp[int(word[i]-'a')];
        }
        if(head->isend){return true;}
        return false;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        node* head=root;
        for(int i=0; i<prefix.length(); i++){
            if(head->alp[int(prefix[i]-'a')]==nullptr){
                return false;
            }
            head=head->alp[int(prefix[i]-'a')];
        }
        return true;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

#include<iostream>
using namespace std;

class A
{
    public:
        struct Assign
        {
            public:
                int a=10;
                float b=20.5;
            private:
                double c=30.0;
                long int d=40;
         };
         struct Assign ALT;
};

class B: public A
{
public:
    int x = 10;
private:
    float y = 20.8;
};

int main()
{
   B myobj;
   A obj;
   //cout<<myobj.a<<endl;
   //cout<<myobj.b<<endl;
   //cout<<obj.a<<endl;
   //cout<<obj.b<<endl;
   cout<<myobj.ALT.a<<endl;

    return 0;
}

    enter code here

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to struct

How to search for an element in a golang slice "error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to check for an empty struct? error: expected primary-expression before ')' token (C) Init array of structs in Go How to print struct variables in console? Why Choose Struct Over Class? How to return a struct from a function in C++? Initializing array of structures