Click here to Skip to main content
15,347,088 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have one doubt related to the OOPS. Why we need to point base class object to the derived class. We can directly create derived class object and can perform required operation.(as per my understanding)


public class abc
        public int abc123 = 0;
        public void qwerty()
            MessageBox.Show("from base");
    public class pqr:abc
        public int pqr123 = 0;
        public void qwerty123()
            MessageBox.Show("from derived");

In above example if we add
abc qw = new pqr();
we can not access derived class members.

Please let me know if you have any idea about it.
Updated 4-Oct-11 5:05am

abc qw = new pqr();

Because, although you have created an object of type pqr you have assigned it to an object of type abc. So, you are telling the compiler that you will only access properties that are accessible to an abc type. This is a language restriction which is described in Bjarne Stroustrup's C++ page[^].
Sujeet Pardeshi 5-Oct-11 1:55am
I got it.
E.g. base a=new Derived();
in above example even though we are pointing derived class object to the base class, we can access only base class member.
In above case Base can be either abstract class or interface or any some other base class.

Thanks for the reply...:):)
6 down vote accepted

If I tell you I have a dog, you can safely assume that I have a dog.

If I tell you I have a pet, you don't know if that animal is a dog, it could be a cat or maybe even a giraffe. Without knowing some extra information you can't safely assume I have a dog.

similarly a derived object is a base class object (as its a sub class), so can be pointed to by a base class pointer. however a base class object is not a derived class object so can't be assigned to a derived class pointer.

(The creaking you will know hear is the analogy stretching)

Suppose you now want to buy me a gift for my pet.

In the first scenario you know it is a dog, you can buy me a leash, everyone is happy.

In the second scenario I haven't told you what my pet is so if you are going to buy me a gift anyway you need to know information I havent told you (or just guess), you buy me a leash, if it turns out I really did have a dog everyone is happy.

However if I actually had a cat then we now know you made a bad assumption (cast) and have an unhappy cat on a leash (runtime error)
Sujeet Pardeshi 4-Oct-11 9:28am
Thanks for the reply.
But in above case we can directly create the object of derived class and performed required computation.
My basic question is, Is there any scenario in which we need to create base class object which point to the derived class object??

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900