Home » C++ programs » C++ constructor and destructor programs

Set values of data members using default, parameterized and copy constructor in C++

Here, we are going to learn how to set values to the data members in a class using default, parameterized and copy constructor in C++?
Submitted by IncludeHelp, on September 27, 2018

Create a class and set values to the private data members using a default, parameterized and copy constructor in C++.

This is an example of C++ constructors, here we have a class named person and private data members name and age. In this example, we will set values to name and age through the default, parameterized and copy constructors.

Here, we will create three objects p1, p2 and p3. p1 will be initialized with a default constructor, p2 will be initialized with a parameterized constructor and p3 will be initialized with the copy constructor.

Program:

#include <iostream>
#include <string.h>
using namespace std;

class person{
	private:
		char name[30];
		int age;
	
	public:
		//default constructor
		person(){
			strcpy(name,"None");
			age = 0;
		}
		//parameterized constructor
		person(char n[], int a){
			strcpy(name, n);
			age = a;
		}
		//copy constructor
		person(person &p){
			strcpy(name, p.name);
			age =p.age;
		}
		//function to display person details
		void print(void){
			cout<<name<<" is "<<age<<" years old."<<endl;
		}
};

//Main function
int main(){
	//creating objects
	person p1; //default constructor will be called
	person p2("Amit Shukla",21); //parameterized constructor will be called
	person p3(p2); //copy constructor will be called
	
	//printing
	cout<<"object p1..."<<endl;
	p1.print();
	cout<<"object p2..."<<endl;
	p2.print();	
	cout<<"object p3..."<<endl;
	p3.print();	
	
	return 0;
}

Output

object p1...
None is 0 years old.
object p2...
Amit Shukla is 21 years old.
object p3...
Amit Shukla is 21 years old.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.