Reputation: 451
I have class A and B.
class A{
public:
foo();
};
class B : public A{
public:
int x;
};
Assume that there is an object from B class in a test file.How should I call foo function?
object.foo(); // or
object.A::foo();
Other questions: When do we call a function like that?What if I do multiple inheritance?
Upvotes: 1
Views: 96
Reputation: 58251
class B inherits public members of class A, so function foo()
also belongs to class B and can be called using B class's object.
B b;
b.foo();
You need to know inheritance in c++. Its just same as
b.x;
See x
and foo()
both are member of object b
even b
is object of Class B and its possible because Class B inheritance features from Class A, In your code function foo()
.
Note Class A has only one member function foo()
A a;
a.foo();
Is valid, But
a.x;
Is not valid
EDIT: Multi-level inheritance Class C inherits Class B and Class B inherits Class A, then
class C : public B{
public:
int y;
};
C c;
c.foo(); // correct
Is also valid.
And
c.x;
c.y;
Also valid, x
, y
, foo()
all are member of Class C.
Notice: What I told you is multi-level Multiple inheritance in C++ is different. Also three access specifiers in C++ are very important in case of inheritance: public private protected in c++
Upvotes: 1
Reputation: 126412
Simply object.foo()
, and there's not much more to add:
B object;
object.foo();
Upvotes: 3