Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

constructor question

Hi,

I have a base and derived class like:

    class Base {
        Base();
        Base(int x, int y);
    };

I have a derived class like:

    class Derived : public Base {
        Derived();
    };

If I understand correctly, Derived's constructor will call Base's constructor automatically. I want Derived to call Base's alternate constructor, something like:

      class Derived : public Base {
          Derived(int x, int y)
          {
               Base(x,y);
               // rest of my stuff
           }
      };

how does that work?

Thanks

ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

ASKER

Where do I put that initializer though, just in the cpp file?:

////      header
class Derived : public Base {
    Derived(int x, int y);
};

///     cpp file
Derived::Derived(int x, int y) : Base (x, y)
{
 
}



Thanks
Just where you implement the function if you want it in .cpp file your sample is correct - you can't put it in declaration if implementation is elsewhere
>>Where do I put that initializer

In the .cpp file where you need it. You might have two versions of your constructor, one that calls the (appropriate!) base constructor and one that does not call it or calls a different one, e.g.

Derived::Derived(int x, int y) : Base (x, y)
{
 
}

Derived::Derived() : Base ()
{
 
}

Derived::Derived(int x) : Base (x, 0)
{
 
}