class C : public B
Q: i have a variable holding a C object , how do i get a variable of type B, connected to the same object?
A: simple assignment will do, but sliced!
Here’s the call to C constructor
Using pointers — B* ptr = &obj;
Using references — B& ref = obj;
Q: Can 2 non-ref variables refer to the same object in memory?
A: I don’t think so. You need the address. nonrefs don’t know how to use addresses.
A: I guess it’s similar to java primitives. No way to create 2 int variables connected to the same int object
A: I feel the slicing problem occurs when you copy objects, but what about when you have just one object but multiple pointers?
Now we are ready to differentiate virtual vs redefining. Building on our example, say B has a public method m(), redefined in C. What is ptr->m() or ref.m()?
* difference — virtual is C::m() ^ redefinition is B::m(),
* difference — virtual is runtime binding ^ redefinition is compile time binding
Now a note on java. Java has only overloading (compile time binding) vs overriding ie virtual. C++ offers virtual ^ overloading ^ redefining. Last 2 are compile time binding.
ptr + virtual -} C // B ptr to a C object, to call a virtual method m()
ref + virtual -} C
nonref + virtual -} B
ptr + redefine -} B
ref + redefine -} B
In summary, only ptr/ref + virtual is really virtual. Not virtual if you use a nonref OR if you drop “virtual” keyword.
Destructors behave just like methods —
ptr + virtual -} C
ptr + non-virtual -> B. See P104 [[NittyGritty]]