Base class constructor variables

Started by
2 comments, last by rip-off 16 years, 4 months ago
Hi how should I go about coding it if I wish to pass in variables to my base class constructor?

class Base
{
   int myInt;

public:
   Base(int A)
   {
      myInt = A;
   };
};

class Bar : public Base
{
public:
    Bar()
    {
       Base(10);
    }
};

Does this work? I didn't put a default Base() constructor, because I want to restrict the declaration of all Base class to fill in a int like: Base b(132); Base z; <- Will give error, hence it force user to not declare it this way Thanks
Advertisement
Initializer lists.

class Base{   int myInt;public:   Base(int A) : myInt(A) {}};class Bar : public Base{public:    Bar() : Base(10) {}};
Thanks alot ToohrVyk. It works :D
Just to note:
class Bar{    // ...    Bar()    {       Base(10);    }    // ...};


This is valid syntax, it creates an anonymous Base instance with the value ten passed to its constructor. An example where you might use this syntax is adding value objects to a container, like so:
std::vector<Sphere> spheres;spheres.push_back(Sphere(radius));

This topic is closed to new replies.

Advertisement