C++ vs Java
C++ vs Java
Result: 11 9 10 Result: 11 8 8
2. Even though b's value of a was decremented to 9 before the slicing, the sliced copy a2
has no knowledge of B's behavior, and fields inherited from B are copied by value
3. When calling “a2.f()”, it invokes A::f() (not B::f()), because a2 is now just of type A.
Therefore, the result is 10 (9 + 1 = 10)
→ RESULT: 11 9 10
Java:
In Java, there is no object slicing as in C++. Java uses references rather than direct value
assignment when working with objects, so “a2 = b” does not create a sliced copy; instead, a2
refers to the same B object
→ RESULT: 11 8 8
class A {
protected:
int a;
public:
A() { a = 10; }
virtual int f() { a++; return a; } // Use virtual for
polymorphism
int geta() { return a; }
};
class B : public A {
public:
int f() { a--; return a; }
};
int main() {
A a;
A* a2; // Pointer to base class A
B b;
a.f();
b.f();
a2 = &b; // Assign address of b to a2 (no slicing, a2 points
to b)
a2->f(); // Calls B::f() because a2 points to B, b.a becomes
8
std::cout << a.geta() << " " << b.geta() << " " << a2->geta()
<< std::endl;
return 0;
}
class A {
protected:
int a;
public:
A() { a = 10; }
virtual int f() { a++; return a; } // Use virtual for
polymorphism
int geta() { return a; }
};
class B : public A {
public:
int f() override { a--; return a; } // Override for runtime
polymorphism
};
int main() {
A a;
B b;
A& a2 = b; // Use a reference to base class A, but point it to
b
a.f();
b.f(); // B::f(), b.a becomes 9
a2.f(); // Calls B::f() because a2 refers to B, b.a becomes
8
std::cout << a.geta() << " " << b.geta() << " " << a2.geta() <<
std::endl;
return 0;
}