Doubt in Inheritance

I was having a little doubt in Inheritance.

Say I have this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A
{
protected:
    int X
public:
    int ShowX () {return X;}
};

class B: public A
{
public: 
    int ShowX() {retuen X;}

};


Will the X returned by B will be a member of B or of A?

In other terms:
When one class inherits another, are the (protected & public) members of the base class copied into the Inherited class, or just made accessible to
it?
In a way, both. Inheritance is an "is a" relationship. Making B inherit from A means to make B into a kind of A. So A::X and B::X refer in this case to the same thing. For example:
1
2
3
4
5
B b;
b.X=12;
A *a=(A *)&b;
std::cout <<b.X<<std::endl
    <<a->X<<std::endl;

By the way, A::ShowX() isn't virtual, so B::ShowX() will never get called.
Last edited on
What did you do in line 3?
A *a=(A *)b;

I can'd understand (A *)b

By the way, A::ShowX() isn't virtual, so B::ShowX() will never get called.

Can't we simply call it as b.ShowX?
I thought we could...
Whoops. Sorry. Force of habit, since I always use pointers with polymorphism. I've edited that line.
If you still don't understand what it does, read up on pointer casting.

Can't we simply call it as b.ShowX?
If A::ShowX() isn't virtual, it can't be overridden, so you'll end up calling it, instead of B::ShowX().
Ok! That explains both of them.

Thanks a lot . . .
Topic archived. No new replies allowed.