-1

I m learning in c++ from the textbook but still confusing

C++ Programme:

using namespace std;
#include<iostream>

class A
{
public:
    A()
    {
        std::cout << "A\n";
    }
};

class B: public A
{
public:
    B()
    {
        std::cout << "B is derived class\n";
    }
};


int main()
{

    A * a=new A();  //valid 
    B * b=new B();  //valid

    A * aa=new B(); //valid    why?
    B * bb=new A(); //invalid  why?                                  run time error: invalid conversion from ‘A*’ to ‘B*’ [-fpermissive]

    return 0;
}

this line

A * a=new A();  //valid 

use because I want to access class a

and

this line

B * b=new B();  //valid 

use because I want to access class b

and

I m writing this line learning purpose I don't know but this is valid why??

A * aa=new B();  //valid

and

I m writing this line learning purpose I don't know but this is not valid why??

B * bb=new A(); //not valid

please explain the last two lines still confusion?

programme link: https://onlinegdb.com/Sy8xkt38L

user207421
  • 305,947
  • 44
  • 307
  • 483
Raju
  • 37
  • 1
  • 11
  • 1
    `B * bb=new A(); //invalid why?` - because an A isn't a B. – WhozCraig Mar 28 '20 at 07:39
  • 7
    Sounds like you need a [good C++ book](https://stackoverflow.com/q/388242/9716597). The "is-a" relationship is a very fundamental OOP concept. – L. F. Mar 28 '20 at 07:40
  • Replace `A` with `Shape` and `B` with `Rectangle`. Rectangle is a Shape, but a Shape is not necessarily a Rectangle. – selbie Mar 28 '20 at 07:40
  • To add up on the comment from @L.F. : as a beginner, you should **not** use `new` to allocate object. With modern C++, this should be used only in very specific situations. Just instanciate with `A a;` – kebs Mar 28 '20 at 07:43
  • 1
    @L.F. According to the first sentence they already have a book. (Whether good or not, I don't know. Probably not if it starts with `new`.) – walnut Mar 28 '20 at 07:43

1 Answers1

3

This

class B: public A

effectively says all B's are A's, Its like

class Lion : public Animal

says all lions are animals.

So this is OK

Animal* a = new Lion(); 

because all lions are animals. It's safe to assume that a lion is an animal. But this is not OK

Lion* l = new Animal(); 

because not all animals are lions. You can't take any old animal and pretend it's a lion.

john
  • 85,011
  • 4
  • 57
  • 81