Calling base class constructor

Posted by The Void on Stack Overflow See other posts from Stack Overflow or by The Void
Published on 2010-04-25T10:15:50Z Indexed on 2010/04/25 10:23 UTC
Read the original article Hit count: 191

In the program below, is the line

Derived(double y): Base(), y_(y)

correct/allowed? That is, does it follow ANSI rules?

#include <iostream>

class Base
{
 public:
  Base(): x_(0)
  {
   std::cout << "Base default constructor called" << std::endl;
  }
  Base(int x): x_(x)
  {
   std::cout << "Base constructor called with x = " << x << std::endl;
  }

  void display() const
  {
   std::cout << x_ << std::endl;
  }

 protected:
  int x_;      
};

class Derived: public Base
{
 public:
  Derived(): Base(1), y_(1.2)
  {
   std::cout << "Derived default constructor called" << std::endl;
  }
  Derived(double y): Base(), y_(y)
  {
   std::cout << "Derived constructor called with y = " << y << std::endl;
  }

  void display() const
  {
   std::cout << Base::x_ << ", " << y_ << std::endl;
  }

 private:
  double y_;      
};

int main()
{
 Base b1;
 b1.display();
 Derived d1;
 d1.display();
 std::cout << std::endl;
 Base b2(-9);
 b2.display();
 Derived d2(-8.7);
 d2.display();

 return 0;
}

© Stack Overflow or respective owner

Related posts about inheritance

Related posts about derived-class