I believe I have a slicing problem, and I am not sure how to fix it. I have summarized the issue from my actual program into the example below.
#include <iostream>
#include <vector>
using namespace std;
class Base {
public:
void Use(void) {
cout << "Using Base :(\n";
}
};
class First_Derived : public Base {
public:
void Use(void) {
cout << "Using First_Derived!\n";
}
};
class Second_Derived : public Base {
public:
void Use(void) {
cout << "Using Second_Derived!\n";
}
};
class A {
public:
vector<Base *> Base_Objects;
};
class B {
public:
vector<Base *> Base_Objects;
};
int main() {
// Create and populate A_Object
A A_Object;
A_Object.Base_Objects.push_back(new First_Derived());
A_Object.Base_Objects.push_back(new Second_Derived());
// Create and populate B_Object with objects in A_Object.Base_Objects
B B_Object;
for (vector<Base *>::iterator i = A_Object.Base_Objects.begin(); i != A_Object.Base_Objects.end(); ++i) {
B_Object.Base_Objects.push_back(*i);
}
// Run the Use() function for the first object in B_Object.Base_Objects
(*B_Object.Base_Objects[0]).Use();
// Get command terminal to pause so output can be seen on Windows
system("pause");
return 0;
}
The output is Using Base :(
but I expected Using First_Derived!
. I believe the issue is that once the First_Derived
object is stored in the Base_Objects
vector, it loses it's unique Use()
function, because it is getting converted to a Base
type? Is there a solution to this? I have attempted to apply some of the solutions listed in What is object slicing? but I dont believe I am applying them correctly.