Object Slicing Example in C++
#include <iostream>
#include <string>
class Base {
public:
Base(const std::string& msg) : message(msg) {}
virtual void display() {
std::cout << "Base: " << message << std::endl;
}
private:
std::string message;
};
class Derived : public Base {
public:
Derived(const std::string& msg, const std::string& extra) : Base(msg), extraMessage(extra) {}
void display() override {
std::cout << "Derived: " << extraMessage << std::endl;
}
private:
std::string extraMessage;
};
int main() {
Derived derivedObj("Base Message", "Derived message");
Base baseObj = derivedObj; // Pass by Value, Object slicing happens here
baseObj.display(); // Calls Base::display()
Base* baseObj1 = &derivedObj; // Pass by ref
baseObj1->display(); // Calls Derived::display()
return 0;
}
Output:
Base: Base Message //Sliced Object's output
Derived: Derived message