Parameterized constructor

Like a function, a constructor can be parameterized, i.e. have parameters. We have already learned about a special kind of parameterized constructor – the copy constructor.

Syntax

class ClassName {
    public:
        // create a constructor
        ClassName(type var1, type var2, type var3) {
            // Constructor code
        }
};

int main() {
    ClassName obj(val, val, val)

    return 0;
}

Example: Parameterized Constructor

#include <iostream>
using namespace std;

class Cube {
    private:
        int length, width, height;
    public:
        Cube(int a, int b, int c) {
            length = a;
            width = b;
            height = c;
        }

        int getVolume() {
            return length * width * height;
        }
};

int main() {
    Cube c1(2, 4, 6);
    Cube c2(3, 5, 8);

    cout << c1.getVolume() << endl;
    cout << c2.getVolume() << endl;

    return 0;
}
Output
48
120