Interview Question: Casting in C++

Sample Question #173 (programming – C++)

Consider the following class definitions in C++:

class Computer {

class Laptop : public Computer {

Computer sony;
Laptop vaio;

You may assume both Computer and Laptop are well-defined.

What’s wrong with the following two assigments?

1. Computer * pC = &vaio;

2. Laptop * pL = &sony;

This entry was posted in Sample Qs. Bookmark the permalink.

One Response to Interview Question: Casting in C++

  1. Brett says:

    1. This is implicit upcasting; it’s fine.
    2. This is implicit downcasting, and it’s not allowed in C++. An explicit cast must be used:
            Laptop * pL = (Laptop *) &sony;

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