user3016214
user3016214

Reputation: 69

difference between inherited and own variables of classes

Can someone explain me the difference between own variable of the class and inherited variable? For example in this code:

class First
{
public:
    int test;

    First::First()
    {
        test = 5;
    }
};

class Second : public First
{
public:
    void setTest(int test)
    {
        Second::test = test;
    }
    int Second::GetTestFirst()
    {
        return First::test;
    }
    int Second::GetTestSecond()
    {
        return Second::test;
    }
};
int main()
{
    int input;
    Second * sec = new Second;
    cin >> input;
    sec->setTest(input);   //for example 15
    std::cout << sec->GetTestFirst();
    std::cout << sec->GetTestSecond();
    return 0;
}

What is the difference between output of GetTestFirst() and GetTestSecond()? Is it pointing to same memory block? And if it is the same thing, which one is better to use?

Upvotes: 0

Views: 101

Answers (2)

Wojtek Surowka
Wojtek Surowka

Reputation: 21003

There is no difference - a Second object has only one test member, inherited from First. So saying

return First::test;

is redundant - you can just use

return test

(without this as the other answer states - this is not necessary as well). Also you should not use

Second::GetTestFirst()

and similar. The compiler knows perfectly that it is compiling Second.

GetTestFirst()

is enough. As far as I can see all First:: and Second:: in your code are not necessary. And the last observation: in C++ you should not use dynamic memory unless you need to. Instead of

Second * sec = new Second;

you should use

Second sec;

and . instead of -> later.

Upvotes: 5

Alican
Alican

Reputation: 286

GetTestFirst() and GetTestSecond() does the same thing since test variable only defined inside the base class. Proper way to address that variable would be using this keyword;

return this->test;

Upvotes: 0

Related Questions