I've got a problem understanding inheritance.

#include <iostream.h>
class A
{
    public:
    int x;
};

class S1: public A
{
    public:
    int x;
};

class S2: public S1
{
    public:
    int x;
};

int main()
{
    S2 obj;
    cout << obj.x;
    return 0;
}

In the code above, I basically want to use all the x's. but, obj.x will only allow me to use the x of class S2. How can I use the x of S1 and A (i) inside the class (ii) outside the class using an object of S2.

Also, while using static variables, how do we initialize them outside the class?

Is it like this?

class A
{
    public:
    static int x;
};

A::x = 10;

***inside the class of S2

obj.x will only allow me to use the x of class S2

I think its because you created the oject of class S2, it seems like variables are overriding here...you cant refer the variables of the base class without their ojectes

Here is how to refer to members of specific classes

int main()
{
    S2 obj;
    obj.A::x = 123;
    std::cout << obj.A::x;
    return 0;
}
commented: Thanks. THat's what I needed! :D +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.