3

When you have a derived class, is there an simpler way to refer to a variable from a method other than:

BaseClass::variable 

EDIT
As it so happens, I found a page that explained this issue using functions instead: Template-Derived-Classes Errors. Apparently it makes a difference when using templates classes.

1
  • could you make your question more specific, such that you illustrate the fact that it relates to template derived classes? Thanks. Commented Oct 27, 2008 at 20:25

2 Answers 2

10

If the base class member variable is protected or public than you can just refer to it by name in any member function of the derived class. If it is private to the base class the compiler will not let the derived class access it at all. Example:

 class Base { protected: int a; private: int b; }; class Derived : public Base { void foo() { a = 5; // works b = 10; // error! } }; 

There is also something to be said for keeping all member variables private, and providing getters and setters as needed.

Also, beware of "hiding" data members:

 class Base { public: int a; }; class Derived : public Base { public: int a; }; 

This will create two variables named a: one in Base, one in Derived, and it will likely lead to confusion and bugs.

Sign up to request clarification or add additional context in comments.

1 Comment

Just to clarify, accessing a private member of a base class will result in a compiler error. The compiler will not ignore it and look for another match.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.