You are here:

C++/Heritage Question

Advertisement


Question
Dear Vijayan,

Below is an example I took from a book.
Could you confirm that out of those 8 statements below, only the 3 I marked are errors?

class Base{
public:
  void am(){...};
  .....
};
class Derived{
public:
  void af(){...};
  .....
};

void gm(Base b){...}
void gf(Derived d){...}

Base b;
Derived d;

gm(b);
gm(d); // error
gf(b); //error
gf(d);

b.am();
d.am();
b.af();// error
d.af();

thanks.

Answer
i presume, you intended

  class Derived : public Base { .... };

and that Base and Derived are default constructible, Base is copy constructible.

with the above assumptions,

Base b;
Derived d;

gm(b); // ok, exact match
gm(d); // ok, convert Derived to Base (slice)
gf(b); //error, no conversion from Base to Derived
gf(d); // ok, exact match

b.am(); // ok, call member function of Base
d.am(); // ok, call inherited member function
b.af(); // error, af is not a member of base
d.af(); // ok, call member function  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.