Copy constructor
#include <iostream>
using namespace std;
class Exam {
int x, y;
public:
// Constructor
Exam(int p, int q) {
x = p;
y = q;
// Copy Constructor
Exam (Exam &g1) { // Use const reference
g1.x++; // Copying the x value
g1.y++; // Copying the y value
// Display function
void display() {
//
cout << x <<" " <<y << endl;
}
};
int main() {
Exam e1(6, 9);
Exam e2(7, 2); // Original object
Exam e3(e1); // Copy constructor is called here
[Link](); // Display values of original object
// [Link](); // Display values of copied object
return 0;
Operator overloadif
#include <iostream>
using namespace std;
class Point {
private:
int x; // X-coordinate
int y; // Y-coordinate
public:
// Constructor
Point(int xCoord, int yCoord) : x(xCoord), y(yCoord) {}
// Overloading the + operator
Point operator+(const Point &other) {
return Point(x + other.x, y + other.y); // Create a new Point
// Function to display the point
void display() {
cout << "(" << x << ", " << y << ")" << endl;
};
int main() {
Point p1(2, 3); // Create first point (2, 3)
Point p2(4, 5); // Create second point (4, 5)
Point p3 = p1 + p2; // Use overloaded + operator to add points
cout << "Point 1: ";
[Link](); // Display first point
cout << "Point 2: ";
[Link](); // Display second point
cout << "Result of addition: ";
[Link](); // Display result of addition
return 0;
++
#include <iostream>
using namespace std;
class Counter {
private:
int count; // Variable to hold the count
public:
// Constructor to initialize the counter
Counter(int c = 0) : count(c) {}
// Overloading prefix ++ operator
Counter& operator++() {
++count; // Increment the count
return *this; // Return the current object
// Overloading postfix ++ operator
Counter operator++(int) {
Counter temp = *this; // Create a copy of the current object
count++; // Increment the count
return temp; // Return the copy (old value)
// Function to display the count
void display() const {
cout << "Count: " << count << endl;
};
int main() {
Counter c1(5); // Create a Counter object with initial count of 5
cout << "Initial ";
[Link](); // Display initial count
// Using prefix ++
++c1; // Increment using prefix
cout << "After prefix increment: ";
[Link](); // Display count after prefix increment
// Using postfix ++
c1++; // Increment using postfix
cout << "After postfix increment: ";
[Link](); // Display count after postfix increment
return 0;