0

I have a class A with method Hello:

class A {
 public:
  void Hello(){
     std::cout << "Hi from class A!" << std::endl;
  }
};

I then have a class B that inherits class A and has its own Hello method:

class B : public A {
 public:
  void Hello(){
     std::cout << "Hi from class B!" << std::endl;
  }
};

I create a new object of class B, and later cast it to be of type class A.

B myB;
A myA = static_cast<A>(myB);

How do I make it so myA.Hello(); prints "Hi from class B!"?

Saddy
  • 1,515
  • 1
  • 9
  • 20
  • 5
    You cannot, for two reasons. First, polymorphism in C++ requires pointers or references. `myA` has been [sliced](https://stackoverflow.com/questions/274626/what-is-object-slicing) and is `A` and nothing else (it's also separate object, copied from `myB`). Second: [Why do we need virtual functions in C++?](https://stackoverflow.com/q/2391679/7976805) A friendly tip: learning C++ by drawing parallels to Java is going to be woe and misery. I strongly suggest forgetting everything you learnt about Java and getting [a good C++ book](https://stackoverflow.com/q/388242/7976805) to learn from. – Yksisarvinen Nov 14 '22 at 01:30
  • 7
    C++ is not Java, objects in C++ work fundamentally differently than they do in Java. You might be surprised to learn that in Java all objects are not really objects, they're just pointers to objects. You can do the exact same thing in C++ using pointers and virtual inheritance (which is a Java dirty secret -- in Java all functions are virtual). You will do yourself a huge, huge favor if you completely forget everything you know about Java when trying to learn C++, else confusion, like this, will exist in perpetuity. – Sam Varshavchik Nov 14 '22 at 01:32
  • Thank you, Yksisarvinen and Sam. I'll try switching it to use a virtual function with pointers. I'll look into the books you suggested; I'm definitely still stuck on the java-mindset while coding C_. – Saddy Nov 14 '22 at 01:36

1 Answers1

1

You should use reference and can call Hello()

    B myB;
    A& myA = static_cast<A&>(myB);
    myA.Hello();

oupput:

Hi from class A!

If you add "virtual" to Hello() of class A,

virtual void Hello() {

you can get output below.

Hi from class B!
shy45
  • 457
  • 1
  • 3