C++ Question...this should be easy for you
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 ?
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.
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.
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
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
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
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement