0% found this document useful (0 votes)
29 views

Assignment On Constructor

The document discusses three types of constructors in C++ - default, parameterized, and copy constructors. The default constructor initializes object attributes by prompting for user input. The parameterized constructor initializes attributes by passing values to the constructor. The copy constructor initializes a new object by copying the attributes of an existing object.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Assignment On Constructor

The document discusses three types of constructors in C++ - default, parameterized, and copy constructors. The default constructor initializes object attributes by prompting for user input. The parameterized constructor initializes attributes by passing values to the constructor. The copy constructor initializes a new object by copying the attributes of an existing object.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

DEFAULT CONSTRUCTOR

// defining the constructor within the class

#include <iostream>

using namespace std;

class student {

int rno;

char name[10];

double fee;

public:

student()

cout << "Enter the RollNo:";

cin >> rno;

cout << "Enter the Name:";

cin >> name;

cout << "Enter the Fee:";

cin >> fee;

void display()

cout << endl << rno << "\t" << name << "\t" << fee;

};

int main()

{
student s; // constructor gets called automatically when

// we create the object of the class

s.display();

return 0;

PARAMETERISED CONSTRUCTOR
// CPP program to illustrate

// parameterized constructors

#include <iostream>

using namespace std;

class Point {

private:

int x, y;

public:

// Parameterized Constructor

Point(int x1, int y1)

x = x1;

y = y1;

int getX() { return x; }

int getY() { return y; }

};

int main()
{

// Constructor called

Point p1(10, 15);

// Access values assigned by constructor

cout << "p1.x = " << p1.getX()

<< ", p1.y = " << p1.getY();

return 0;

Copy Constructor
// 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;

You might also like