C++ constructors explain give examples
A constructor in C++ is a special member function that is automatically called when an object is created. Its purpose is to initialize the object's data members and allocate any resources that the object requires. Constructors have the same name as the class and are declared without a return type.
Here are some examples of constructors in C++:
- Default constructor: This constructor is called when an object is created without any arguments. It initializes the object's data members to their default values.
class Person {
public:
Person() {
name = "";
age = 0;
}
private:
string name;
int age;
};
- Parameterized constructor: This constructor accepts one or more parameters to initialize the object's data members.
class Person {
public:
Person(string n, int a) {
name = n;
age = a;
}
private:
string name;
int age;
};
Person p1("John", 25);
- Copy constructor: This constructor creates a new object as a copy of an existing object.
class Person {
public:
Person(const Person& p) {
name = p.name;
age = p.age;
}
private:
string name;
int age;
};
Person p1("John", 25);
Person p2 = p1; // copy constructor called
- Constructor overloading: This is when a class has multiple constructors with different parameters.
class Person {
public:
Person() {
name = "";
age = 0;
}
Person(string n) {
name = n;
age = 0;
}
Person(int a) {
name = "";
age = a;
}
Person(string n, int a) {
name = n;
age = a;
}
private:
string name;
int age;
};
Person p1; // default constructor called
Person p2("John"); // parameterized constructor with one argument called
Person p3(25); // parameterized constructor with one argument called
Person p4("John", 25); // parameterized constructor with two arguments called
原文地址: https://www.cveoy.top/t/topic/v0K 著作权归作者所有。请勿转载和采集!