Kelly Elton
Kelly Elton

Reputation: 4427

c++ redefine a class

I would like to redefine a class in c++ (non clr). Here's the reason

class BabyClass
{
    public:
        string Name;
        int getSiblings(MainClass &mclass)
        {
            int c = mclass.size();
            for(int i=c;i>0;--i)
            {
                if(mclass.at(i).Name != Name)
                    cout << mclass.at(i).Name;
            }
        }
}
class MainClass
{
    public:
       vector<BabyClass> babies;
}

now of course this isn't my real code, but I think you can see the problem. I want my baby class to have access to the main class, the problem is at compile time it doesn't know the MainClass exists, so to fix it normally I would put the MainClass above the BabyClass, but if I do that I can't have a vector of BabyClass's because the compiler wouldn't know about the BabyClass. I know with functions you can do something like

int function(string hello);

then later

int function(string hello)
{
    code
}

or use virtual functions and such. Any idea's how I would do this with classes? Thanks.

And by the way, I know someone is going to ask if it's really necessary, so yes, it is.

Upvotes: 1

Views: 1114

Answers (1)

Chubsdad
Chubsdad

Reputation: 25497

Try this arrangement which forward declares MainClass.

class MainClass;

class BabyClass 
{ 
public: 
 string Name; 
 int getSiblings(MainClass &mclass);
};

class MainClass 
{ 
public: 
 vector<BabyClass> babies; 
};

int BabyClass::getSiblings(MainClass &mclass) 
{ 
     // your code which uses mclass
 return 0;
} 

int main(){}

BTW, this is not called redefine. The technique is to forward declare and then define it.

Upvotes: 6

Related Questions