c++ data structure help please?

Questions about programming languages and debugging
Locked
User avatar
Swan
Knight of the Sword
Knight of the Sword
Posts: 827
Joined: 18 Oct 2006, 16:00
17
Contact:

c++ data structure help please?

Post by Swan »

Code: Select all

struct Employee
{
string name; // Employee name
int vacationDays, // Vacation days allowed per year
daysUsed; // Vacation days used this year
Employee() // Constructor
{ name = "";
vacationDays = 10;
daysUsed = 0;
}
};

Code: Select all

struct PopInfo
{
string name; // City name
long population; // City population
PopInfo(string n, long p) // Constructor with 2 parameters
{ name = n;
population = p;
}
};
The above code/program accepts arguments where as the first one does not....I am not 100% sure as to why....
To the wicked, I am merely too knowledgeable in their ways.

User avatar
ayu
Staff
Staff
Posts: 8109
Joined: 27 Aug 2005, 16:00
18
Contact:

Post by ayu »

When you create a structure, there are generally two kinds of constructors. There are default constructors, and there are programmed defined constructors.

In your first code example you are using the default constructor to set the variables in the structure Employee, which means that when you create an instance of Employee without any arguments, it will be created using the default constructor

Code: Select all

Employee() // Constructor
{ 
       name = "";
       vacationDays = 10;
        daysUsed = 0;
} 
And since you did not create a programmer defined constructor, you can not send it arguments.


In the second example you only have a programmer defined constructor, which would mean that if you create an instance of PopInfo without any arguments, it will create an instance with "empty" variables (calling the empty default constructor), and if you create it with arguments it will call the constructor you defined yourself

Code: Select all

PopInfo(string n, long p) // Constructor with 2 parameters
{
      name = n;
      population = p;
} 

I created an example that demonstrates a typical struct in use

Code: Select all

#include <string>
#include <iostream>

using namespace std;

struct Person
{
	string name;

	Person()
	{
		name = "noname";
	}

	Person(string n)
	{
		this->name = n; 
	}
};

int main()
{
	Person p;
	Person p2("Teddy");

	cout << p.name << endl;
	cout << p2.name << endl;

	return 0;
}
"The best place to hide a tree, is in a forest"

Locked