clyp efor
clyp efor

Reputation: 19

C++ Classes, Default Constructors

To keep it simple and to the point, I have a class

class square
{
public:
    square(int s); // parameterized constructor with default parameter = 0
    square(); 

private:
    int side; // holds the side of the square (whole number)
};

square::square() {

    side = 0; 
}

square::square(int s){

    side = 0; // parameterized constructor with default parameter = 0
}

and in the main I have the following:

int main()
{
    square sq1;// declare 4 objects of type square named sq1, sq2, sq3, and sq4 initializing the third one to 10
    square sq2;
    square sq3(10);
    square sq4;
}

The problem is that if I comment out square(); in the class, the square sq1, sq2 and sq4 won't work. I need to initialize square(int s) as a default constructor set to 0 and only use that for all four square sq's. How would I go about fixing that?

Upvotes: 0

Views: 236

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

In any case you have to define a default constructor. From the C++ (2017) Standard (15.1 Constructors)

4 A default constructor for a class X is a constructor of class X for which each parameter that is not a function parameter pack has a default argument (including the case of a constructor with no parameters). If there is no user-declared constructor for class X, a non-explicit constructor having no parameters is implicitly declared as defaulted (11.4). An implicitly-declared default constructor is an inline public member of its class.

So to make the constructor with parameter a default constructor just supply a default argument in the declaration of the constructor. For example

class square
{
public:
    square(int s = 0 ); // parameterized constructor with default parameter = 0

private:
    int side; // holds the side of the square (whole number)
};

The constructor itself can be defined like

square::square( int s ) : side( s )
{
}

Also you can declare the constructor with the function specifier explicit to prevent implicit conversion from the type int to the type square.

class square
{
public:
    explicit square(int s = 0 ); // parameterized constructor with default parameter = 0

private:
    int side; // holds the side of the square (whole number)
};

Upvotes: 0

Pavan Chandaka
Pavan Chandaka

Reputation: 12731

Remove the default constructor (square(); ) completely and modify your parametrized constructor definition as shown below.

square::square(int s = 0) {

    side = s; // parameterized constructor with default parameter = 0
}

Upvotes: 1

Related Questions