basic question on reference counting + virtual^redefining


class C : public B

Q: i have a variable holding a C object , how do i get a variable of static type B, connected to the same object?
A: simple assignment will do, but sliced!

Here’s the call to C constructor

C obj;

Using pointers — B* ptr = &obj; //upcasting by ptr
Using references — B& ref = obj; // upcasting by reference

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]]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s