Don't know what a empty default constructor does

  • Thread starter Thread starter torquerotates
  • Start date Start date
  • Tags Tags
    Empty
AI Thread Summary
The discussion clarifies the purpose of an empty default constructor in C++. It explains that while the compiler automatically generates a default constructor if none is provided, explicitly defining one can serve as a placeholder for future initialization needs. The participants note that default constructors are often unnecessary when a class has other constructors that initialize data members. It emphasizes that the presence of a regular constructor can adequately handle data initialization. Overall, understanding the role of default constructors helps clarify object-oriented programming practices.
torquerotates
Messages
207
Reaction score
0

Homework Statement

I don't know what the


Person::Person()
{
}

means. I thought a default constructor is meant to initialize private data fields. There is not initialization. That code segment is from
#include <iostream>
#include <string>

using namespace std;

class Person
{
public:
Person();
Person(string pname, int page);
string get_name() const;
int get_age() const;
private:
string name;
int age; /* 0 if unknown */
};

Person::Person()
{
}

Person::Person(string pname, int page)
{
name = pname;
age = page;
}

string Person::get_name() const
{
return name;
}

int Person::get_age() const
{
return age;
}

void main()
{
Person f("Fred", 20);
cout << f.get_name() << " is " <<
f.get_age() << " years old.\n";
}
 
Physics news on Phys.org
It's not necessary, the compiler will silently create this behind the scenes.
It is good practice to write this, just as a place holder for when you do have to add some initialisation code.
 
Oh i see. So default constructors are usually unnecessary? I'm guessing that its because that regular constructor already initializes the data in the data field.
 

Similar threads

Replies
2
Views
2K
Replies
2
Views
1K
Replies
8
Views
1K
Replies
3
Views
1K
Replies
2
Views
3K
Replies
7
Views
2K
Back
Top