0

I have a class that have a attribute that its type is another class, and I would like to be able to set its value to be a instance of a child of this class.

I prefer to explain with a example:

// Some kinds of glasses
class Glass {
  public:
    virtual void punch() {
      cout << "break" << endl;
    }
}

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

// The main class
class Car {
  public:
    Glass glasses;
}

// main method
int main(void) {
  Car car;
  ArmoredGlass armoredGlass;

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

  return 0;
}

I cannot change the value of car.glasses to a Glass child class, and that is what I would like to do.

Panda Soli
  • 61
  • 6
  • 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
  • 61
  • 6