Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Multiple parents with same variable name

class A{
    protected:
    int var;
};

class B{
    protected:
    int var;
};

class C : public A, public B {};

What happens here? Do the variable merges? Can I call one in specific like, B::var = 2, etc.

like image 668
nahpr Avatar asked Sep 03 '12 23:09

nahpr


People also ask

Does C allow multiple inheritance?

Master C and Embedded C Programming- Learn as you go So the class can inherit features from multiple base classes using multiple inheritance. This is an important feature of object oriented programming languages such as C++.

When a function with the same name appears in more than one base class in multiple inheritance?

Inheritance Ambiguity in C++ In multiple inheritances, when one class is derived from two or more base classes then there may be a possibility that the base classes have functions with the same name, and the derived class may not have functions with that name as those of its base classes.

Can a child class have multiple parents C++?

C++ Multiple Inheritance In C++ programming, a class can be derived from more than one parent.


1 Answers

You class C will have two variables, B::var and A::var. Outside of C you can access them like this (if you change to public:),

C c;
c.A::var = 2;

Attempting to access c.var will lead to an error, since there is no field with the name var, only A::var and B::var.

Inside C they behave like regular fields, again, with the names A::var and B::var.

like image 141
user1071136 Avatar answered Sep 21 '22 01:09

user1071136