C++ Class User Defined Constructors

Introduction

Constructors can have arbitrary parameters; in which case we can call them user- provided constructors:

#include <iostream> 

class MyClass //w w w.j av  a  2 s. c  o  m
{ 
public: 
    int x, y; 
    MyClass(int xx, int yy) 
    { 
        x = xx; 
        y = yy; 
    } 
}; 
int main() 
{ 
    MyClass o{ 1, 2 }; // invoke a user-provided constructor 
    std::cout << "User-provided constructor invoked." << '\n'; 
    std::cout << o.x << ' ' << o.y; 
} 

In this example, our class has two data fields of type int and a constructor.

The constructor accepts two parameters and assigns them to data members.

We invoke the constructor with by providing arguments in the initializer list with MyClass o{ 1, 2 };.

Constructors do not have a return type, and their purposes are to initialize the object of its class.




PreviousNext

Related