Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C++ Constructors and Destructors, Exercises of Object Oriented Programming

A Constructor is a method for a class that gets called automatically whenever an object of the class is created.

Typology: Exercises

2021/2022

Uploaded on 09/12/2022

leonpan
leonpan 🇺🇸

4

(12)

286 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
C++ Constructors
and Destructors
CPSC 1070, Donald House, Clemson University!
10/23/19
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download C++ Constructors and Destructors and more Exercises Object Oriented Programming in PDF only on Docsity!

C++ Constructors

and Destructors

CPSC 1070, Donald House, Clemson University

Some Nomenclature

  • Constructor^ is a method for a class that gets called automatically whenever an

object of the class is created. It is used to give the class’s data initial values.

  • Destructor^ is a method for a class that gets called automatically whenever an

object of the class is deleted. It is used to delete any memory that the class has

dynamically allocated.

  • Default Constructor^ is a constructor that takes no parameters, and gives the

class’s data default initial values. It is always called for each array element when an

array of the class’s objects is created.

  • Initializing Constructor^ is a constructor that takes a set of parameters that are used

to initialize the class’s data to non-default values.

  • Copy Constructor^ is a constructor that takes another object of the same class as

its reference parameter, and makes the new object an exact copy of the argument.

  • Static member^ is a member variable of a given class that is shared by all objects of

that class, instead of being unique to a particular object.

Destructors

A Destructor is a method for a class that gets called automatically whenever an object of the class is deleted. Its name is always the class name preceded by a ~, it takes no arguments, and there is no return value, not even void. class Point{ private : int x, y; public : Point(); ~Point(); }; destructor

Constructor and Destructor Definition

A Constructor is defined like any other method, but it never has a return value (not even

void).

Point::Point(){ x = y = 0; } Point::Point( int x0, int y0){ x = x0; y = y0; } Point::Point( const Point &pt){ x = pt.x; y = pt.y; }

A Destructor is also defined like any other method, but has neither arguments nor a

return value (not even void).

Point::~Point(){ } default constructor initializing constructor copy constructor destructor, note there is nothing to do in this case

Constructor Usage

A Constructor is called whenever a variable of its class is created. Here are some examples Point p0; Point p1(10, 50); Point plist[20]; Point p2(pt); Point *pt0 = new Point; Point *pt1 = new Point(10, 50); Point *pt2 = new Point(pt); Point *ptable = new Point[20]; default constructor, p0 will have coordinates (0, 0) initializing constructor, p1 will have coordinates (10, 50) default constructor, each element of array plist will have coordinates (0, 0) default constructor, *pt0 will have coordinates (0, 0) initializing constructor, *pt1 will have coordinates (10, 50) default constructor, every element of array ptable will have coordinates (0, 0) copy constructor, p2 will have the same coordinates as the Point pt copy constructor, *pt2 will have the same coordinates as the Point pt

Default Parameters

Any function or method in C++ can be defined with Default Parameters. These specify

the value a parameter will take if the corresponding argument to a call to the function is

missing. Here is an example of how the constructor for Point could be written so the

default and initializing constructors use the same code:

Point::Point( int x0 = 0 , int y0 = 0 ): x(x0), y(y0){ }

This declaration simulates the default constructor, since x0 and y0 are not supplied, x

and y take on their default value (0, 0):

Point p0;

This declaration simulates the initializing constructor, since x0 and y0 are supplied, x

and y take on the values (10, 50):

Point p1(10, 50);

This declaration is odd but it works. x0 is supplied, but not y0, therefore x and y take

on the values (10, 0):

Point p2(10);

Example Polygon Class Initialization of Static Variable int Polygon::numpolygons = 0 ;

Example Polygon Class Default Constructor // Default constructor makes sure vertices pointer is NULL // and that the number of vertices is 0. // It also increments the count of the number of polygons. Polygon::Polygon(): vertices( NULL ), nverts( 0 ){ numpolygons++; } initializer list increment count of polygons

The initializer list is the preferred way to initialize the

member variables of an object.

Note: It is very important to initialize all pointer

member variables of an object, so that they have

meaningful values. All pointers should be set to NULL

in the initializer list, unless the constructor is going to

set the pointer in the body of its code.

Example Polygon Class Adding a Single Vertex void Polygon::addvertex( const Point &pt){ Point *oldverts = vertices; vertices = new Point[++nverts]; for ( int i = 0 ; i < nverts - 1 ; i++) vertices[i] = oldverts[i]; vertices[nverts - 1 ] = pt; delete []oldverts; } increment number of vertices and allocate space for additional vertex copy the old vertex array to the new vertex array store the new vertex at the end of the new array free up the space for the old array

Example Polygon Class Accessing and Setting Vertices Point *Polygon::getvertices() const { Point *vtxcopy = new Point[nverts]; for ( int i = 0 ; i < nverts; i++) vtxcopy[i] = vertices[i]; return vtxcopy; } void Polygon::setvertices( int n, Point *verts){ if (n != nverts){ delete []vertices; nverts = n; vertices = new Point[nverts]; } for ( int i = 0 ; i < nverts; i++) vertices[i] = verts[i]; } allocate space for a copy of the vertices copy the vertex array return the copied array if the number of new vertices is different from the current number, delete the old vertices array and make a new one the right size copy in the contents of the verts array

Code Using Polygon Class #include “Polygon.h" #include using namespace std; int main(){ Polygon poly1; Point pt; int nx, ny; // read initial vertices and add to Polygon one by one cout << "Enter poly1 vertices: "; cin >> nx >> ny; while (!cin.eof()){ pt.set(nx, ny); poly1.addvertex(pt); cin >> nx >> ny; } poly1.print(); cout << endl; cout << "currently there are " << poly1.getnumpolygons() << “ polygons" << endl; // get number of vertices, and vertices from the // polygon and and print them out int n = poly1.getnverts(); Point *pts = poly1.getvertices(); cout << "poly1 has " << n << " vertices" << endl; cout << "they are: "; for ( int i = 0 ; i < n - 1 ; i++){ pts[i].print(); cout << ", "; } pts[n - 1 ].print(); cout << endl; // give another polygon the same vertices as the // original polygon and print Polygon poly2; poly2.setvertices(n, pts); cout << "poly2 vertices are: "; poly2.print(); cout << endl; // delete the copied vertices delete []pts; // make a new polygon that is a copy of the first // polygon using the copy constructor Polygon *poly3 = new Polygon(poly1); cout << "poly3 vertices are: "; poly3->print(); cout << endl; cout << "currently there are " << poly1.getnumpolygons() << “ polygons" << endl; // now delete the new polygon cout << "deleting poly3" << endl; delete poly3; cout << "currently there are " << poly1.getnumpolygons() << “ polygons" << endl; return 0 ; }

Code Would be Distributed Over Several Files Point.cpp Polygon.cpp Declarations Definitions Usage Point.h trypolygon.cpp Polygon.h

Example C++ Program

Polygon Exercising Program

Download from the schedule page