Question Why can't I access a variable declared in derived class with the object of base class

lucky10101

New member
Joined
Jul 8, 2017
Messages
1
Programming Experience
Beginner
Hi, Good Evening everyone


I have created two classes namely Shape, Rectangle with Draw() method in both the classes, Rectangle class is a deried class from Shape. I have declared a public variable in Rectangle called num and initialised a value to it.


In the main class I have created an object of type Shape class in following manner.


Shape s = new Rectangle();


Now when I am trying to access num variable of rectangle class it gives error saying “ /Users/apple/Projects/Practice/Practice/Program.cs(33,33): Error CS1061: 'Shape' does not contain a definition for 'num' and no extension method 'num' accepting a first argument of type 'Shape' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Practice)”


My Understanding : The statement new Rectangle(); creates an object of type Rectangle in the memory and its reference is stored in object s of type Shape. So the object s should have access to variable num defined in rectangle class. Please make me understand this concept why we can’t access num variable from Object of type Shape.


Pls find the attached screenshot.


Screen Shot 2017-07-08 at 9.57.46 PM.png
 
Back
Top Bottom