1

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?

g3d
  • 453
  • 2
  • 6
  • 14
  • 3
    What problem are you having? This is really basic and you should simply try it. Not to mention read [your C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)... – Lightness Races in Orbit Mar 19 '13 at 16:51
  • I would highly encourage you to go to the last link I added in my answer about Difference between `private, public and protected inheritance in C++` – Grijesh Chauhan Mar 19 '13 at 17:15

2 Answers2

3

Simply object.foo(), and there's not much more to add:

B object;
object.foo();
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
1

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++

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208