Saturday, April 19, 2025

C++ OO Default Constructor Parameters

C++ allows you to specify default parameter values for constructor parameters. This means that if you don't explicitly provide a value for a constructor parameter, the default value will be used. 


#include <iostream>

using namespace std;

class Cls{
    private:
        string name;
        int age;

    public:
        Cls(string def_name = "Michael", int def_age = 40) {
            name = def_name;
            age = def_age;

            cout << "Default name: " << name << endl;
            cout << "Default age: " << age << endl;
        }
};

int main() {

    Cls Object;

    return 0;
}

This code defines a C++ class called Cls with a constructor that has default parameter values for def_name and def_age. The constructor initializes the private member variables name and age with the default values if no arguments are provided when an instance of the Cls class is created.

In the main() function, an instance of the Cls class called Object is created using the default constructor. Since no arguments are provided, the default values for def_name and def_age will be used.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...