Hello guys, I'm fairly new to c++, and just started learning inheritance. I came up with a quick question here. In the code I created below, can the base class display the value of x in showBase() method? Or would it be impossible?
Thank you!
#include <iostream>
class Base{
public:
void showBase(){
std::cout << "value of x: ";
}
};
class Derived:public Base{
public:
int x;
private:
Dervied(int n){
x = n;
}
};
int main(){
Derived d(3);
Base b;
b.showBase(); // or I could even do d.showBase() right?
return 0;
}
can the base class display the value of x in showBase() method? Or would it be impossible?
No, a class can never assume that anything has been derived from it. A class knows only itself and its bases.
No, it is not impossible. That is what virtual functions are for:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
class Base{
public:
virtualvoid show() {}
};
class Derived : public Base {
int x;
public:
Derived(int n) : x(n) {}
virtualvoid show() { std::cout << x; }
};
int main() {
Derived d( 3 );
Base* pb = d;
pb->show();
return 0;
}
Serious logical issue here:
1 2 3 4 5 6
int main(){
Derived d(3);
Base b;
b.showBase();
return 0;
}
The d IS-A Derived object.
The d IS-A Base object, because Derived inherits Base.
The b and d are two entirely separate objects.
The b IS-A Base object and nothing more. It cannot know anything about any Derived objects.
You have a wallet. You have a neighbors with wallets. Should your wallet know how much money a neighbor wallet has? No.
No, b.showBase(); is not there to tell about the d.
Lets do it again:
1 2 3 4 5 6 7 8 9
int main(){
Derived d(3);
Derived fubar(42);
Derived snafu(7);
Base xyz;
Base b;
b.showBase();
return 0;
}
@gunnerfunner
Thanks for the advice :)) I did compile my program before posting but when I copied the code from my compiler and pasted in here it all appeared in one line for some reason so I just decided to copy it word by word and maybe I made some mistakes as I was doing that hehe ;)
@keskiverto
I really really appreciate it!
Now I realized I was misunderstanding the relationship between the two...
Thank you so much for all the information and help! :DD