Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I alias a member of a base class in a derived class?

Tags:

c++

c++11

Say I have the following classes:

template <class T>
class Base {
  protected:
    T theT;
    // ...
};

class Derived : protected Base <int>, protected Base <float> {
  protected:
    // ...
    using theInt = Base<int>::theT;     // How do I accomplish this??
    using theFloat = Base<float>::theT; // How do I accomplish this??
};

In my derived class, I would like to refer to Base::theT using a more intuitive name that makes more sense in the Derived class. I am using GCC 4.7, which has pretty good coverage of C++ 11 features. Is there a way of using a using statement to accomplish this kind of how I tried in my example above? I know that in C++11, the using keyword can be used to alias types as well as eg. bring protected base class members into the public scope. Is there any similar mechanism for aliasing a member?

like image 384
Nicu Stiurca Avatar asked Dec 09 '12 04:12

Nicu Stiurca


People also ask

Can a derived class be a friend of base?

Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them. In the following example, class d is derived publicly from class b . Class b is declared a public base class by this declaration.

How do you access base class members in a derived class?

You can use both a structure and a class as base classes in the base list of a derived class declaration: If the derived class is declared with the keyword class , the default access specifier in its base list specifiers is private .

Can a class be both a base class and a derived class?

A derived class can have only one direct base class.

Can derived class initialize base member?

The members of base aggregate class cannot be individually initialized in the constructor of the derived class.


1 Answers

Xeo's tip worked. If you are using C++ 11, you can declare the aliases like so:

int   &theInt   = Base<int>::theT;
float &theFloat = Base<float>::theT;

If you don't have C++11, I think you can also initialize them in the constructor:

int   &theInt;
float &theFloat;
// ...
Derived() : theInt(Base<int>::theT), theFloat(Base<float>::theT) {
  theInt = // some default
  theFloat = // some default
}

EDIT: The slight annoyance is that you can't initialize the the value of those aliased members until the main body of the constructor (ie, inside the curly braces).

like image 193
Nicu Stiurca Avatar answered Sep 27 '22 18:09

Nicu Stiurca