0

Why do I get the error "No default constructor exists for class "Sub", even though I have the constructor for Sub class"

    class Base{
    private:
        int x;      
    public:
        Base(int number) 
        {
            x = number;
        }
        virtual void print(void) = 0;       
    };
    
    
    class Sub: public Base{
    
    public:
        Sub(int x): Base(x) {       
        }
        void print() 
        {
           cout << "Testing" << endl;    
        }
        
    
    };

1 Answers1

1

A default constructor is one taking NO arguments. A default constructor is one which requires no provided arguments.

Base() and Base(args = default) are both considered default constructors, as no arguments are required. Please note the second one is Pseudo Code.

   class Base{
    private:
        int x;      
    public:
        Base(int number) 
        {
            x = number;
        }
        virtual void print(void) = 0;       
    };
    
    
    class Sub: public Base{
    
    public:
        Sub(int x): Base(x) {       
        }
        void print() 
        {
           cout << "Testing" << endl;    
        }
        
    
    };

Your code definitely does not have a default constructor.

Declaring a constructor automatically disables the compiler-created default contructor.

More info:

https://en.cppreference.com/w/cpp/language/default_constructor

https://www.geeksforgeeks.org/constructors-c/

https://www.ibm.com/docs/en/zos/2.2.0?topic=only-default-constructors-c

https://www.w3schools.com/cpp/cpp_constructors.asp

https://learn.microsoft.com/en-us/cpp/cpp/constructors-cpp

https://www.learncpp.com/cpp-tutorial/constructors/

  • 2
    I'd also mention that declaring a constructor disables the automatic definition of the default constructor. – Raildex Jun 17 '21 at 16:30
  • 1
    Also note `your_class(int i = 0){}` is also considered a ***default constructor***, while taking arguments. – Ranoiaetep Jun 17 '21 at 21:34