Hi there,

Please check my program. When i compile it i am getting error.

Cannot find default constructor to initialzie base class.

#include <iostream.h>
#include <conio.h>

class Parent
{

    protected:
    double num;

   public:
      Parent(double n)                                      
      {
        num = n;
      }

      void sub()
      {
        num -= 2.0;
         cout << "num = " <<num <<endl;
      }
};


class Child : public Parent
{

    //protected:

   public:
      Child()
      {
        cout << "num = " <<num <<endl;
      }

      void display()
      {
        cout << "agian num : " <<num <<endl;
      }

};

void main()
{

    Parent p(5.0);
   p.sub();

    Child c;
   c.display();


getch();
}

Recommended Answers

All 3 Replies

Child implicitly calls the default constructor for Parent, but Parent doesn't have a default constructor because you explicitly defined a single argument constructor. The quickest solution would be to modify your current constructor to have a default argument such that it also acts as a default constructor:

Parent(double n = 0)                                      
{
    num = n;
}
    Parent(double n = 0)
    {
    num = n;
    }

If I assign 0 to n then how can i pass value to it when i make object ??

It is a default parameter. If you do not send anything then it will default to zero but if you pass a value it will get the value passed. To pass the value you would need to have a child constructor like this.

Child(int n) : Parent(n)
{
    cout << num;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.