Petre Popescu
Petre Popescu

Reputation: 2002

C++ calling super class

I am mostly a Java and AS3 programmer but right now I am working in C++ for something and I stumbled upon a problem. I have a base class (let's call it ClassA) that has a private variable var1. In this class I have a method getVar1() that returns a pointer to that variable.

Next I have another class that extends Base (let's call it ClassB). How do I call the getVar1() from the super class? In java it is as simple as this.var1 = super.getVar1().

I read that it is like var1 = ClassA::getVar1(), but I am not sure if this is OK for work with variables (aka the pointers can change).

Thanks.

Upvotes: 1

Views: 6447

Answers (3)

Giel
Giel

Reputation: 397

Here is a small example showing what happens: - A initializes x at 10 - B initializes x at 20 below you can see how virtual function calls work out and how calling your parent works out (even if you initialized the value differently)

the biggest thing to keep in mind is that even if you call your super function (A::GetX), it still uses the value from your own class (B::x)

class A
{
public:
    A::A() : x(10) {}
virtual int GetX() {return x*2;}
protected:
    int x; 
};

class B : public A
{
public:
    B::B() : A()
    {
        x = 20;
    }
    virtual int GetX() {return x;}
};

int _tmain(int argc, _TCHAR* argv[])
{
    A* a1 = new A();
    B* b1 = new B();
    int test1 = a1->GetX(); // returns 20 (because x is 10, but function doubles value)
    int test2 = b1->GetX(); // returns 20 (because x is initialized at 20)
    return 0;
}

now if we change the B::GetX to:

virtual int GetX() {return A::GetX();}

We get the following result:

int _tmain(int argc, _TCHAR* argv[])
{
A* a1 = new A();
B* b1 = new B();
int test1 = a1->GetX(); //returns 20 (as previously)
int test2 = b1->GetX(); // return 40 (x is initialized by B at 20, but then the
                        // A:GetX is called, which doubles the result)
return 0;
}

Upvotes: 2

AndersK
AndersK

Reputation: 36082

getVar1() should be enough

class ClassB : public ClassA
{
...
   void foo() { yourvartype* v = getVar1(); ... }
};

if you OTOH have defined another getVar1() in ClassB then ClassA::getVar1() should be used to help the compiler to identify which function to call.

Upvotes: 3

sinned
sinned

Reputation: 503

it's ok to call it ClassA::getVar1().

However, if you want the java-way, you can make the method "virtual". This means whenever you write getVar1(), it doesn't depend on the Type you wrote in front of it (so at compile time) but it depends on the type of the object when you call it (at runtime). For this reason, c++ keeps an internal v-table to find the appropriate method. It's equivalent to the java way and called late-binding.

Upvotes: 6

Related Questions