Don't know what a empty default constructor does

  • Thread starter Thread starter torquerotates
  • Start date Start date
  • Tags Tags
    Empty
Click For Summary
SUMMARY

The discussion clarifies the purpose of an empty default constructor in C++. The code segment provided demonstrates a class named Person with both a default constructor and a parameterized constructor. The empty default constructor Person::Person() does not initialize any member variables, as the compiler automatically generates one if none is defined. However, defining it is considered good practice for future modifications, allowing for potential initialization code to be added later.

PREREQUISITES
  • Understanding of C++ class structures
  • Familiarity with constructors in C++
  • Knowledge of member variable initialization
  • Basic understanding of C++ syntax and compilation
NEXT STEPS
  • Explore C++ constructor overloading techniques
  • Learn about the role of destructors in C++
  • Investigate the implications of default member initializers in C++11
  • Study best practices for class design in C++
USEFUL FOR

C++ developers, computer science students, and anyone interested in understanding object-oriented programming principles in C++.

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);
count << 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 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 23 ·
Replies
23
Views
9K
  • · Replies 12 ·
Replies
12
Views
2K
Replies
8
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K