0

I am trying to replace an attribute of a class (attribute that is a glass class type) with another daughter class of the glass class.

NOTE: I usually use #ifndef, but to leave the smaller example I didn't use

main.cpp

#include <iostream>
#include "Car.h"
#include "ArmoredGlass.h"
using namespace std;


int main(int argc, char** argv) {
  Car car;
  ArmoredGlass armoredGlass;

  car.glasses = armoredGlass;
  car.glasses.punch();

  return 0;
}

Car.h

#include "Glass.h"

class Car {
  public:
    Glass glasses;
};

Glass.h

#include <iostream>
using namespace std;

class Glass {
  public:
    virtual void punch() {
      cout << "break" << endl;
    }
};

ArmoredGlass.cpp

#include <iostream>
using namespace std;

class ArmoredGlass : public Glass {
  public:
    virtual void punch() {
      cout << "nothing..." << endl;
    }
};

Reponse:

break

Expected response:

nothing...

Ruli
  • 2,403
  • 12
  • 27
  • 35
Panda Soli
  • 11
  • 2
  • 1
    You need to read about object slicing and member function dynamic binding. – 273K May 29 '22 at 22:49
  • 2
    Does this answer your question? [Issues with virtual function](https://stackoverflow.com/questions/20039215/issues-with-virtual-function) or perhaps [Store derived class objects in base class variables](https://stackoverflow.com/questions/8777724/store-derived-class-objects-in-base-class-variables) – JaMiT May 29 '22 at 23:06
  • @JaMiT - The links you sent helped, but I don't wanna create a list, but change a class object to an object from another class that derives from it. – Panda Soli May 29 '22 at 23:30
  • @PandaSoli The first link does not make use of a list. It simply takes an object whose type is the base class (`Person`) and tries to change it to an object from a derived class (`Student`). When a member function is invoked on the object after the assignment, the member from the base class is invoked instead of the member from the derived class. Does that not ring familiar? – JaMiT May 29 '22 at 23:30

1 Answers1

0

main.cpp

#include <iostream>
#include "Car.h"
#include "ArmoredGlass.h"
using namespace std;


int main(int argc, char** argv) {
  Car car;
  Glass* armoredGlass = new ArmoredGlass();

  car.glasses = armoredGlass;

  car.glasses.punch();
  cout << car.glasses[0].state << endl;

  return 0;
}

Car.h

#include "Glass.h"

class Car {
  public:
    Glass* glasses;
};
Panda Soli
  • 11
  • 2