• Advertisement
Sign in to follow this  

C++ Question...this should be easy for you

This topic is 4328 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi...I learned everything from java and I'm now learning C++ there's one thing I can't do calling a parent method from the child ex : class Parent{ virtual void meth(){...} }; class Child:public Parent{ void meth(){[INSERT CALL HERE]}; }; just like we do with super(...) in java is it possible ?

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
You can explicitly tell a class to run a function from one of it's superclasses:

void Child::meth()
{
Parent::meth();
}


That requires you to know which parent you want to call, and will break if you rearrange your heirarchy.

I usually typedef the parent type within my child classes as "ParentClass", that way, I can call ParentClass::myfunc(), to keep a bit of standardization between classes.

Share this post


Link to post
Share on other sites
The class "Child" inherits everything from the base class, therefore Child literally has a "meth" function. So, you can just call "meth()" from anywhere inside the class. For example

class base
{
protected:
void print(int x)
{
std::cout << x << std::endl;
}
};

class base2 : public base
{
public:
base2()
{
print(2);
print(5);
}
};


int _tmain()
{
base2 *temp = new base2();
delete (temp);
}




this would print
2
5
to the console window

So that's about it


EDIT: you can also do it the way the people who beat me to it showed you

Share this post


Link to post
Share on other sites
The difference is that if the method is overridden by the child class, you have to do it the way the first two posts show.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement