Cpp - class Default Constructors


You can set an object up without specifying parameters:

Cart shoppingCart; 
Rectangle rect; 

This calls the default constructor of the class, which is a constructor with no parameters.

If you did not declare a constructor for the class, the compiler creates a default constructor for you.

The default constructor the compiler adds takes no action; it is a constructor with no parameters whose body was empty.

The default constructor is a constructor that takes no parameters.

You can define it yourself or be provided one as a default from the compiler.

If you define any constructor, the compiler does not provide a default constructor for you.

In that case, if you want a default constructor (with no parameter), you must define it yourself.

If you did not define a destructor, the compiler provides an empty destructor for you.

The following code shows how to add constructor to Cart class.


#include <iostream> 

class Cart /*  w  ww .  j a va  2  s.  c  o  m*/
    Cart(int initialAge); 
    int getSpeed(); 
    void setSpeed(int speed); 
    void pedal(); 
    void brake(); 
    int speed; 
// constructor for the object 
Cart::Cart(int initialSpeed) 
// destructor for the object 
    // do nothing 
// get the trike's speed 
int Cart::getSpeed() 
    return speed; 
// set the trike's speed 
void Cart::setSpeed(int newSpeed) 
    if (newSpeed >= 0) 
        speed = newSpeed; 
// pedal the trike 
void Cart::pedal() 
    setSpeed(speed + 1); 
    std::cout << "\nPedaling; speed " << getSpeed() << " mph\n"; 
// apply the brake on the trike 
void Cart::brake() 
    setSpeed(speed - 1); 
    std::cout << "\nBraking; speed " << getSpeed() << " mph\n"; 
// create a trike and ride it 
int main() 
    Cart shoppingCart(5); 
    return 0; 


Related Topic