#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// initialize variables with parameterized constructor
Wall(double len, double hgt) {
length = len;
height = hgt;
}
// copy constructor with a Wall object as parameter
// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
double calculateArea() {
return length * height;
}
};
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);
// copy contents of wall1 to wall2
Wall wall2 = wall1;
// print areas of wall1 and wall2
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();
return 0;
}
// Copy constructor
Point(const Point &p2) {x = p2.x; y = p2.y; }
int getX() { return x; }
int getY() { return y; }
};
Point(const Point &p2) {x = p2.x; y = p2.y; }
// Example: Explicit copy constructor
#include<iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body
Sample(Sample &t) //copy constructor
{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1; copy constructor called
obj2.display();
return 0;
}
// Example: Implicit copy constructor
#include<iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1;
obj2.display();
return 0;
}
Code Example |
---|
Cpp :: How to reverse a string in c++ using reverse function |
Cpp :: terminal compile c++ |
Cpp :: string stream in c++ |
Cpp :: vector fin element c++ |
Cpp :: how to get an element in a list c++ |
Cpp :: c++ create multidimensional vector |
Cpp :: sieve of eratosthenes algorithm in c++ |
Cpp :: include cpp |
Cpp :: decltype in c++ |
Cpp :: c++ programming language |
Cpp :: all possible permutations of characters in c++ |
Cpp :: print 2d array c++ |
Cpp :: on component begin overlap c++ |
Cpp :: c++ default parameters |
Cpp :: c++ remove numbers from vector if larger than n |
Cpp :: stoi cpp |
Cpp :: c++ triple |
Cpp :: c++ pi float |
Cpp :: how to sort in descending order in c++ |
Cpp :: palindrome checker in c++ |
Cpp :: stoi() c++ |
Cpp :: c++ if else |
Cpp :: how to compile opencv c++ in ubuntu |
Cpp :: cpp getter as const |
Cpp :: c++ uint32_t |
Cpp :: print pattern and space in cpp |
Cpp :: c plus plus |
Cpp :: show stack c++ |
Cpp :: how to make window resizable in sdl |
Cpp :: c for loop decrement |