Cpp - class Default Constructors

Introduction

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.

Demo

#include <iostream> 

class Cart /*from  w ww .  j  av  a  2s. c o  m*/
{ 
public: 
    Cart(int initialAge); 
    ~Cart(); 
    int getSpeed(); 
    void setSpeed(int speed); 
    void pedal(); 
    void brake(); 
private: 
    int speed; 
}; 
  
// constructor for the object 
Cart::Cart(int initialSpeed) 
{ 
    setSpeed(initialSpeed); 
} 
  
// destructor for the object 
Cart::~Cart() 
{ 
    // 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); 
    shoppingCart.pedal(); 
    shoppingCart.pedal(); 
    shoppingCart.brake(); 
    shoppingCart.brake(); 
    shoppingCart.brake(); 
    return 0; 
}

Result

Related Topic