Anda di halaman 1dari 33

Constructors

Problem Statement
Write a program that calculates the distance in terms of feet and inches.

Preliminary Analysis

An object must be directly representable using a single type A distance has two attributes: Feet (integer) Inches (float) When an object cannot be directly represented by any of the available types, build a class!

Building Classes

Begin by defining variables to store the attributes of the object being represented (a distance) int feet; float inches;

Building Classes

We then wrap these variables in a class declaration:

class distance { private: int feet; float inches; public: void getData() { cout<<"Enter Feet\n"; cin>>feet; cout<<"Enter Inches\n"; cin>>inches; } void showData() { cout<<feet<<" feet and "<<inches<<"inches\n"; } };

Declaring this class does not allocate memory for a Distance It just tells the compiler what Distance is and what are its attributes

Data Hiding

Hiding data from parts of the program that do not need to access it Classes have a public section and a private section Items (data or functions) declared in the public section are accessible to users of the class i.e., they can be accessed from outside the class Items declared in the private section are inaccessible to users of the class i.e., they can only be accessed from within the class Data members should go in the private section, to prevent programmers from writing programs that access data members directly All class members are private by default

Defining an Object
A programmer can now write:
Distance d1; and object d1 can be visualized as follows: d1
feet inches

The data members feet and inches within Distance are uninitialized

Problem

At present, a Distance declaration: Distance d1; leaves Distances data members uninitialized To auto-initialize them to a default value, we can use a special function called a constructor

Constructors

A constructor function is a class member function whose task is to initialize the class data members Since it returns nothing, a constructor has no return type (not even void) The name of a constructor is always the name of the class (in this case Distance())
Distance () { feet=0; inches=0.0; }

Contd

Since they specify the first thing a user of the class needs to know (i.e., how to define class objects), constructor prototypes are usually the first function members listed in the public section of the class

Object Definitions
A programmer can now write:
Distance d1; and object d1 can be visualized as follows: d1
feet inches

0
0.0

The class constructor is automatically called whenever a class object is created

#include<iostream.h> class Distance { private: int feet; float inches; public: Distance () { feet=0; inches=0.0; }
void getData() { cout<<"Enter Feet\n"; cin>>feet; cout<<"Enter Inches\n"; cin>>inches; }

void showData() { cout<<feet<<" feet and "<<inches<<"inches\n"; } };


void main() { Distance d1; d1.showData();(if no constructor, it will generate an error) d1.getData(); d1.showData();

Problem 2
At present, we can only initialize Distance to a default value: Distance d1; We have no means of initializing Distance to any other value. To initialize Distance to a particular value (e.g., 10,3.5), we can overload the constructor with a second definition

Constructor 2 Definition
To overload the constructor, we just provide a second definition (and prototype) that differs from all other constructors in at least one parameter To initialize the data members of our class, this second constructor must receive the initial values via its parameters The same name can be used to define different functions, provided the signature (the list of the parameter types) of each function is different Distance (int ft, float in) { feet=ft; inches=in; }

Object Definitions
A programmer can now write:

Distance d1; d1.showData(); Distance d2(5,3.9); d2.showData();

and d1 and d2 are defined as follows: d1


feet inches 0 0.0

d2

feet inches

10 3.9

The compiler uses the number of arguments in a declaration to decide which constructor to use in initializing an object

Testing To test this, we can write in main()


void main() { Distance d1; d1.showData(); Distance d2(5,3.9); d2.showData();

d1.getData(); d1.showData();
}

Another way of Writing Constructor Definition

Distance () : feet (0), inches (0) { } Distance (int ft, float in) : feet (ft), inches (in) { }

No-Argument Constructor

If you dont explicitly define any constructors, the compiler automatically generates a default constructor that takes no arguments So in case you do not define any constructors and simply create a Distance object
Distance d1;

The compiler will call a default constructor which does not, however, assign any values to the data members But once youve defined even one kind of constructor (may be a 2-arg constructor),the compiler will no longer create a default no-argument constructor for you

No-Argument Constructor
E.g., if I remove the following from my class declaration Distance () { feet=0; inches=0.0; } And then try to execute the following in main()

Distance d1; d1.showData(); Distance d2(5,3.9); d2.showData();

This will give a compile time error

Default Arguments/Parameters

Any C++ function can provide default values for its input function arguments If a value is not specified in a function call, the default value is assigned and sent to the called function To clear up any confusion to the compiler, a rule is enforced when using default values and multiple arguments All arguments to the right of an argument with a default value must be specified In other words, their can be no "holes" in your default parameter list

This rule helps the compiler determine which arguments to assign values to in a function call

int square(int n=1) { return n*n; }

void main () { cout<<"Enter a number to find its Square\n\n"; int num; cin>>num; cout<<endl; cout<<num<<" suare = "<<square(num); cout<<endl; cout<<endl; }

Using Default Parameters (combining both constructor definitions)

We can combine two functions (constructor without parameters and constructor with parameters) using default parameters of C++

Constructor for the Distance class


Distance (int ft=0, float in=0.0) { feet=ft; inches=in; }

Using Default Parameters

In our main function, we can write:

void main() { Distance d1; d1.showData();

Distance d2(5,3.9); d2.showData();


d1.getData(); d1.showData(); }

The Default Copy Constructor

No-argument constructor initializes data members to constant values. Multi-argument constructor initializes to values passed as arguments. Another way- initialize an object with an other object of the same type no need for special constructor- default copy constructor: a one-argument constructor, whose argument is the object of the same class as constructor.

The Default Copy Constructor


Distance d1(10,2.5); Distance d2(d1); Distance d3 =d1;

Activity

Create a class date with member functions getDate() and printDate(). Define the constructors

Class Destructors

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed Same name as the class but preceded by a tilde (~) Has no arguments and no return type

class X { private: int a; public: X():a(0){} // Constructor for class X ~X(){} // Destructor for class X };

Objects as Function Arguments

class Distance { public: int feet; float inches; public: Distance (int ft=0, float in=0.0) { feet=ft; inches=in; } void getData() { cout<<"Enter Feet\n; cin>>feet; cout<<"Enter Inches\n; cin>>inches; } void showData() { cout<<feet<<" feet and "<<inches<<"inches\n;} void add_dist(Distance, Distance); };

void Distance :: add_dist(Distance d1, Distance d2) { inches = d1.inches + d2.inches; if (inches >= 12.0) { inches -= 12.0; feet++; } feet += d1.feet + d2.feet; } void main() { Distance d1 (8, 7.0); d1.showData(); Distance d2(5,3.9); d2.showData(); cout<<"The sum of d1 & d2 is"; Distance d3; d3.add_dist(d1,d2); d3.showData();}

Returning Objects from Functions

Distance Distance :: add_dist(Distance d2) { Distance temp; temp.inches = inches + d2.inches; if (temp.inches >= 12.0) { temp.inches -= 12.0; temp.feet =1; } temp.feet += feet + d2.feet; return temp;

int main() { Distance dist1,dist3; Distance dist2(11,6.5); dist1.getdist(); //from user dist3 = dist1.add_dist(dist2); return 0; }

Recommended Reading

Robert Lafore, Chapter 6: Objects and Classes Dietel & Dietel, Chapter 9

Anda mungkin juga menyukai