Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
C++ Program - Default, Parameterized, and Copy Constructor
✅ C++ Program to Demonstrate Default, Parameterized, and Copy Constructor
#include <iostream>
using namespace std;
class sample {
private:
string name;
int age;
public:
// Default constructor
sample() {
cout << "Enter name of the student:\n";
cin.ignore();
getline(cin, name);
cout << "Enter age of the student:\n";
cin >> age;
}
// Parameterized constructor
sample(string n, int a) {
name = n;
age = a;
}
// Copy constructor
sample(sample &obj) {
name = obj.name;
age = obj.age;
}
void display() {
cout << "Name: " << name << "\n";
cout << "Age: " << age << "\n";
}
};
int main() {
sample s1;
cout << "=== DEFAULT CONSTRUCTOR ===\n";
s1.display();
sample s2("Esther", 27);
cout << "=== PARAMETERIZED CONSTRUCTOR ===\n";
s2.display();
cout << "=== COPY CONSTRUCTOR ===\n";
sample s3(s2);
s3.display();
}
๐ Explanation:
This C++ program demonstrates the use of three types of constructors in object-oriented programming:
- Default Constructor → Initializes object when no arguments are passed. Here, it asks the user to input values.
- Parameterized Constructor → Allows initialization with specific values while creating the object.
- Copy Constructor → Creates a new object by copying values from an existing object.
๐งพ Sample Output:
Enter name of the student: John Enter age of the student: 22 === DEFAULT CONSTRUCTOR === Name: John Age: 22 === PARAMETERIZED CONSTRUCTOR === Name: Esther Age: 27 === COPY CONSTRUCTOR === Name: Esther Age: 27
๐ Keywords:
C++ constructor example, default constructor, parameterized constructor, copy constructor, OOPs in C++, class and object in C++, beginner C++ programs
๐ Hashtags:
#CPlusPlus #Constructor #OOP #CopyConstructor #ParameterizedConstructor #BeginnerCplusplus
๐ Search Description:
This C++ program demonstrates how default, parameterized, and copy constructors work in object-oriented programming using class and objects with examples and output.
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment