86

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

Thanks.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
small_potato
  • 3,127
  • 5
  • 39
  • 45
  • 17
    Note also that the same technique of the most upvoted answer can be used to define a class inside a class, a struct inside a struct, and a class inside a struct. class and struct are only different for the default visibility of their members (private and public, respectively). – Daniel Daranas Mar 30 '10 at 09:00
  • 9
    ...and their default inheritance type (private and public, respectively). – Christian Rau Jun 07 '13 at 11:03

6 Answers6

102

Something like this:

class Class {
    // visibility will default to private unless you specify it
    struct Struct {
        //specify members here;
    };
};
sharptooth
  • 167,383
  • 100
  • 513
  • 979
70

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.

Afriza N. Arief
  • 7,696
  • 5
  • 47
  • 74
  • So I have a struct with three variables inside and I was able to compile my code with the 'private:' keyword inside. So what are the boundaries of that struct being 'private'? Can the class where the struct is defined access either of those variables? Do I absolutely need public function pointers to deref to functions inside the main class? Basically what I have is a vector of test cases represented by the struct. – JoeManiaci Dec 08 '15 at 22:53
  • As long as you're showing off the idea of defining member functions outside of the class body, perhaps you could edit this answer to also show how to define the struct itself outside of the class body? This is more common in the case of defining nested classes (e.g. iterator types), but might be relevant. – templatetypedef Dec 24 '18 at 01:59
  • @templatetypedef I'm not aware of what you mean.. maybe you can add another answer or edit existing answer to illustrate it. – Afriza N. Arief Dec 24 '18 at 07:31
29

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.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
10

Something like:

class Tree {

 struct node {
   int data;
   node *llink;
   node *rlink;
 };
 .....
 .....
 .....
};
Ben D
  • 465
  • 1
  • 6
  • 20
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • i am trying to do similar kind of thing(creating) huffman tree. I have doubt that how will you create the object of node and how you will made it accesible in main function ? – user3206225 Feb 12 '14 at 00:42
4

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);
 */
TechCat
  • 57
  • 1
3
#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