include <iostream>
#include <cstring>
using namespace std;
class Person{
private:
char *name;
int age;
public:
Person(char * myname, int myage){
int len = strlen(myname) + 1;
name = new char[len];
strcpy(name, myname);
age = myage;
}
Person(){
name = NULL;
age = 0;
cout << "called Person()"<<endl;
}
};
I thought they were both constructors, but can't the constructor be called only once?
c++
Both of them are constructors.
Person(char * myname, int myage)
The above constructor is called when you create a class variable, as shown below. However, name is a string in a dynamically assigned char-type array.
Person bill(name, 20);
On the other hand,
Person()
The above constructor is called when you create a class variable, as shown below.
Person steve;
For your information, a constructor with a format such as Person()
without parameters is called the default constructor.
© 2024 OneMinuteCode. All rights reserved.