-5

I am learning in this moment Oop in C++ and I have been encountring this ( B extendes A )

A* b = new B()

I searched a bit and seen that b have the same functions of B class and therefore I do(!!) understand what is the diffrence between this and

A* a = new A()

BUT do not(!!) understand what is the diffrence between this statment to:

B* b = new B()

Ty for any help :)

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
omersk2
  • 79
  • 1
  • 11
  • 2
    Read more about `virtual` keyword and [virtual method table](https://en.wikipedia.org/wiki/Virtual_method_table) and virtual member functions. Consider spending several days reading a good [C++ programming book](http://stroustrup.com/Programming/). See also some [C++ reference](https://en.cppreference.com/w/cpp) site – Basile Starynkevitch Feb 22 '19 at 13:27
  • 1
    I assume you want to know about Polymorphism. Check e.g. [this question](https://stackoverflow.com/questions/45773839/c-confused-by-this-code-with-polymorphism-pointers-and-object-slicing) – Appleshell Feb 22 '19 at 13:28
  • Please confirm that the class `B` inherits from the class `A`. (`class B : public A {...};`). – Jabberwocky Feb 22 '19 at 13:31
  • You seem to have plenty of confusion: "b have the same functions of B class" is not a correct statement: `b` is an object, not a class. What you need to compare is not statements, but the resulting variables. It would be helpful if you did not use the variable name `b` twice. Give the pointer to `A` a different name, it will clarify your thinking and will let you compare the variables in one program side by side. So: `A* a = new B(); B* b = new B()` –  Feb 22 '19 at 13:31

1 Answers1

3

It just shows that you can use a pointer of the superclass to refer to a child class. This can be useful for polymorphism.

For example, let's say you had a class called "Shape," and you have other classes like "Square" and "Triangle" that extend "Shape." You could write a function that operates on "Shape", and then you could, for example, do this:

void doSomething(Shape* s);

Shape* triangle = new Triangle();
Shape* square = new Square();
doSomething(triangle);
doSomething(square);
Layne Bernardo
  • 676
  • 3
  • 12