-------

-------

  • NA
  • 213
  • 6.9k

which way to access a base class function or variable

Apr 19 2020 2:39 AM
I m a student. Today I Give the Interview and tell me something new about inheritance
 
I said the derived class can not access the base class property or field because below program prove that is why I tell the derived class can not access the base class property or field:
  1. using namespace std;    
  2. #include<iostream>    
  3.     
  4. class baseclass    
  5. {    
  6.   public:    
  7.     int a;    
  8.     baseclass()    
  9.     {    
  10.         std::cout << "baseclass\n";    
  11.     }    
  12. };    
  13.     
  14. class deriveclass: public baseclass    
  15. {    
  16.  public:    
  17.     deriveclass()    
  18.     {    
  19.         std::cout << "derived class\n";    
  20.     }    
  21. };    
  22.     
  23.     
  24. int main()    
  25. {    
  26.     baseclass * a=new baseclass();  //ok    
  27.     deriveclass * b=new deriveclass();  //ok     
  28.     
  29.     baseclass * aa=new deriveclass(); //ok            
  30.     deriveclass * bb=new baseclass(); //not ok    
  31.     
  32.     return 0;    
  33. }  
Link:https://onlinegdb.com/SyfhRDF_U
 
error:
 
main.cpp: In function ‘int main()’: main.cpp:30:36: error: invalid conversion from ‘baseclass*’ to ‘deriveclass*’ [-fpermissive] deriveclass * bb=new baseclass(); //not ok
 
then Interviewer tells me which way to access the base class function or variable?
 
help? 

Answers (3)