prosseek
prosseek

Reputation: 190759

C++ typedef in a class

I use this C++ code for storing x to the variable val.

class Hello
{
  int val;
public:
  Hello(int x) : val(x) {}
};

However, when I saw this code, I cannot see how Super can store value t or o.

template<typename T>
class K : public std::auto_ptr<T>
{
    typedef std::auto_ptr<T> Super;
public:
    K() : Super() { }
    K(T* t) : Super(t) { }
    K(K<T>& o) : Super(o) { }
};

How does this code work?

Upvotes: 1

Views: 1414

Answers (4)

towi
towi

Reputation: 22267

The auto_ptr<T> base class that you are deriving from is a container for an element of class T. That base class has (at least) the constructors defined that you are calling:

The baseclass could be defined like this (actually, it is not, but this constructor-definitions might give you a picture):

template<typename T>
class auto_ptr {
    T* value;
  public:
    auto_ptr() : value(NULL) {}
    auto_ptr(T* t) : value(t) { }
    auto_ptr(auto_ptr<T>& other) : value(other.value) {}
};

So, auto_ptr<T> holds a value of type T. And the three defined constructors take care of:

  • empty/standard constrcution
  • construction from a raw pointer
  • copy of the container

So, and then by telling in you class, that you give Super the name std::auto_ptr<T> that is just an abbreviation to call the respective base class constructor. You could have written

template<typename T>
class K : public std::auto_ptr<T>
{
public:
    K() : std::auto_ptr<T>() { }
    K(T* t) : std::auto_ptr<T>(t) { }
    K(K<T>& o) : std::auto_ptr<T>(o) { }
};

because you are now directly calling the base class constructors. And those we have defined before (and in "real life" are defined with more sense then I did here).

PS: auto_ptr<> is nice as long as you have not seen unique_ptr<>. auto_ptr<>s "bad guy" is it's copy-constructor. Watch out for C++0x...

Upvotes: 1

Xeo
Xeo

Reputation: 131789

Could've been written as

template<typename T>
class K : public std::auto_ptr<T>
{
public:
    K() : std::auto_ptr<T>() { }
    K(T* t) : std::auto_ptr<T>(t) { }
    K(K<T>& o) : std::auto_ptr<T>(o) { }
};

Which is just more verbose to initialize the base class. A typedef is cleaner most of the time if you have to deal with templated base classes.

Upvotes: 4

CygnusX1
CygnusX1

Reputation: 21779

It's because class K inherits from std::auto_ptr<T>. What is happening is that the constructors K(T* t) and K(K<T>& o) call the parent constructor std::auto_ptr<T>(...), which is also called Super thanks to typedef.

Upvotes: 2

Morten Kristensen
Morten Kristensen

Reputation: 7613

The typedef typedef std::auto_ptr<T> Super; means that Super is an auto_ptr of type T. The empty constructor of K initializes Super, if a pointer of type T is given then Super is initialized to be an auto_ptr managing it, and if a reference to K with type T is given then this is passed to Super.

Upvotes: 1

Related Questions