0

I'm learning about C++ and I have a question.

I'm learning about virtual function, and I found saw why do we need virtual functions in cpp.

I tried the answer and now I know why do we need virtual function, but I don't understand that,

below code works fine.

class a
{
public:
    virtual void eat(){  std::cout<<"Eating A food." << endl;
};

class b : public a
{
public:
    void eat(){  std::cout<<"Eating B food." << endl;
}

void eatFunction(a * alpha){ alpha -> eat(); }

int main(void)
{
   a * apple = new a;
   b * banana = new b;

   eatFunction(apple);
   eatFunction(banana);
   return 0;
}

But I just changed class b: public a into class b : a error occured:

error: 'a' is an inaccessible base of 'b'
       eatFunction(banana);

When should I use 'public' inheritance parents class?

And what is different?

Eugene Fitzher
  • 163
  • 3
  • 17
  • Your sample c ode is invalid. There is no type named `apple` or `banana`, so the first two lines of `main()` need to be `a *apple = new a` and `b *banana = new b` respectively. – Peter Jan 30 '20 at 10:14

2 Answers2

2
class b: public a{/*..*/};

b inherits from a publicly (i.e) all of the member functions and vars are inherited in b with the same access specifiers they have in a

class b: a{/*..*/};

b inherits from a privately (i.e) all of the member functions and vars are inherited in b with private access specifiers. So you can't access your function eatFunction outside the class.

asmmo
  • 6,922
  • 1
  • 11
  • 25
  • Thanks! As I understand, there is no any other advantanges using 'public' when I'm not going to make any other function outside of the parent class. So I don't need to use 'public' in the case, right? Of course it will be depends on what I'm going to do, I just wonder. – Eugene Fitzher Jan 30 '20 at 04:59
1
class b : a {};

is the same as

class b : private a {};

Since a is a private base class of b, a b* cannot be implicitly converted to an a*.

R Sahu
  • 204,454
  • 14
  • 159
  • 270