I want to make a copy of one object of one specific type of interface with another of the same interface, here i will write 2 class examples and their output.
This is class Vehicle:
#ifndef _VEHICLE_
#define _VEHICLE_
class Vehicle {
public:
Vehicle(int a): val(a) {}
virtual ~Vehicle() {}
virtual void setVal(int i) = 0;
virtual int getVal() = 0;
protected:
int val;
};
#endif
This is class Car
#ifndef _CAR_
#define _CAR_
#include "Vehicle.h"
class Car : public Vehicle {
public:
Car(int a) : Vehicle(a) {}
~Car() {}
virtual void setVal(int i);
virtual int getVal();
};
#endif
The two methods of the class car just return the value and modifies it like the names suggest.
This is the code of the main
#include <iostream>
#include "Vehicle.h"
#include "Car.h"
using namespace std;
int main()
{
Vehicle * car1 = new Car(0);
Vehicle * car2 = new Car(1);
cout << "val car1 :"<< car1->getVal() << endl;
cout << "val car2 :"<< car2->getVal() << endl;
car1 = car2; //ATTEMPT TO COPY HERE ************************
cout << "val car1 :"<< car1->getVal() << endl;
cout << "val car2 :"<< car2->getVal() << endl;
car2->setVal(6);
cout << "val car1 :"<< car1->getVal() << endl;
cout << "val car2 :"<< car2->getVal() << endl;
car1->setVal(-1);
cout << "val car1 :"<< car1->getVal() << endl;
cout << "val car2 :"<< car2->getVal() << endl;
return 0;
}
The output will be:
val car1 :0
val car2 :1
val car1 :1
val car2 :1
val car1 :6
val car2 :6
val car1 :-1
val car2 :-1
As you can see, there are two different objects of the same interface, but as both objects must be pointers because it is an interface, it´s impossible to make just a copy of the object instead of assign the pointer of the "car2" to the "car1".
My question is if there is any way of doing this, or i just need to make a "clone" method.
thank you for the attention, and sorry if the question is very basic, but i am starting with C++ and some things are a little complicated.
Aucun commentaire:
Enregistrer un commentaire