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?

2
  • 3
    What problem are you having? This is really basic and you should simply try it. Not to mention read your C++ book... Commented Mar 19, 2013 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++ Commented Mar 19, 2013 at 17:15

2 Answers 2

3

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

B object; object.foo(); 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.