Hi! I'm having a proble with constructors. I'm supposed to write a program that has a default constructor, but also one that takes parameters. The program I wrote below is desigend to allow teh setting of age of the person, but when I compile it, I get a message saying "no appropriate default constructor available". Any help greatly appreciated. Umm, and hints on how to correctly insert my posts so code shows up better would be great as well. Thanks again!
Thanks, Bill

#include <iostream>


using std::cout;
using std::cin;
using std::endl;

class person 
{ 
private: 
	char first_name[30]; 
	char last_name[30];
	int itsAge;

public: 
	person(int initialAge);
	~person();

	void setting() 
		{ 
			cout<<"Enter first_name "; 
			cin>>first_name; 
			cout<<"Enter last_name "; 
			cin>>last_name; 
	} 
		
	void printing() 
		{ 
			cout<<"The first_name "; 
			cout<<first_name<<endl; 
			cout<<"The last_name "; 
			cout<<last_name<<endl; 
	} 
};

//constructor of person

person::person(int initialAge) // constructor
{
	itsAge=initialAge;
} 

person::~person() // destructor
{}

void main() 
{ 
	int pause;
	person p1; 
	p1.setting(); 
	p1.printing(); 
	cin>> pause; 
}
Member Avatar for iamthwee
public:
  person();
person::person () // constructor
{
 
}

maybe add?

Well, that certainly worked... Maybe I don't understand constructors aswell as I thought... Does there have to be a default constructor? If I write a constructor that takes a parameter, am I obligated to write a seperate default constructor? Thanks again!
Bill

Well, is this right? If you make a constructor that accepts parameters, then you have to give it a parameter when you declare an object of the class. Unless you have another constructor which is default, then you have the option af adding a parameter, or not?
I hope that's right!
Bill

Does there have to be a default constructor?

Only if you use the default constructor when making objects. If you do Object obj; then Object has to have a default constructor, but if you do Object obj( arg ); then Object only has to have a constructor that takes a single argument.

If I write a constructor that takes a parameter, am I obligated to write a seperate default constructor?

If you need a default constructor and there's already a constructor that takes parameters, you have to write the default constructor. If there's not already a constructor that takes parameters, all classes have a default constructor automatically so you don't need to write it unless it has to do something special beyond what the automatic one does.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.