What is the constructor in this code?

Asked 1 years ago, Updated 1 years ago, 267 views

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++

2022-12-20 08:44

1 Answers

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.


2022-12-20 08:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.