Constructors And Destructors Constructors Information Technology Essay

The main use of constructors is to initialize objects. The function of initialization is automatically carried out by the use of a special member function called a constructor.

General Syntax of Constructor

Constructor is a special member function that takes the same name as the class name. The syntax generally is as given below:

X::X()

In the above example the arguments is optional.

The constructor is automatically named when an object is created. A constructor is named whenever an object is defined or dynamically allocated using the “new” operator.

There are several forms in which a constructor can take its shape namely:

Default Constructor:

This constructor has no arguments in it.  Default Constructor is also called as no argument constructor.

For example:

class Exforsys 

{

    private:

        int a,b; 

    public:

        Exforsys(); 

        …

};

Exforsys :: Exforsys()

{

    a=0;

    b=0;

}

Some important points about constructors:

A constructor takes the same name as the class name.

The programmer cannot declare a constructor as virtual or static, nor can the programmer declare a constructor as const, volatile, or const volatile.

No return type is specified for a constructor.

The constructor must be defined in the public. The constructor must be a public member.

Overloading of constructors is possible. This will be explained in later sections of this tutorial

Destructors

What is the use of Destructors

Destructors are also special member functions used in C++ programming language. Destructors have the opposite function of a constructor. The main use of destructors is to release dynamic allocated memory. Destructors are used to free memory, release resources and to perform other clean up. Destructors are automatically named when an object is destroyed. Like constructors, destructors also take the same name as that of the class name.

General Syntax of Destructors

~ classname();

The above is the general syntax of a destructor. In the above, the symbol tilda ~ represents a destructor which precedes the name of the class.

Some important points about destructors:

Destructors take the same name as the class name.

Like the constructor, the destructor must also be defined in the public. The destructor must be a public member.

The Destructor does not take any argument which means that destructors cannot be overloaded.

No return type is specified for destructors. 

For example:

class Exforsys

{

    private:

        ……………

    public:

        Exforsys()

        { }

        ~ Exforsys()

        { } 

}

public, private and protected access specifiers

In an effort to reduce the number of nonconstructive comments posted by visitors who do not read the entire article or previous comments, I have decided to change the title of the article and the initial summary to something more accurate.

Read also  Overview Of Software Testing Techniques Information Technology Essay

In C++ there are three inheritance access specifiers:

public

protected

private

Any of these three inheritance access specifiers can be modified with the virtual keyword. In my experience interviewing candidates for c++ positions, I’ve learned that the average programmer does not know how these are used, or even what they mean. So I thought I would go over them here.

The three access modifiers public, protected and private are analogous to the access modifiers used for class members.

public

When a base class is specified as public ie: class c : public base {}; the base class can be seen by anyone who has access to the derived class. That is, any members inherited from base can be seen by code accessing c.

protected

When a base class is specified as protected ie: class c : protected base {}; the base class can only be seen by subclasses of C.

private

When a base class is specified as private ie: class c : private base {}; the base class can only be seen by the class C itself.

Examples of how this plays out:

struct X {

public:

void A() {}

};

 

struct Y {

public:

void B() {}

};

 

struct Z {

public:

void C() {}

};

 

struct Q : public X, protected Y, private Z {

public:

void Test()

{

A(); // OK

B(); // OK

C(); // OK

}

};

 

struct R : public Q {

public:

void Test2()

{

A(); // OK

B(); // OK

C(); // NOT OK

 

Q t;

Y *y = &t // OK

Z *z = &t // NOT OK

}

};

 

int main(int argc, char **argv) {

Q t1;

t1.A(); // OK

t1.B(); // NOT OK

t1.C(); // NOT OK

 

R t2;

t2.A(); // OK

t2.B(); // NOT OK

t2.C(); // NOT OK

 

X *x = &t1; // OK

Y *y = &t1; // NOT OK

Z *z = &t1; // NOT OK

 

x = &t2; // OK

y = &t2; // NOT OK

z = &t2; // NOT OK

 

}

Member Functions

Member functions can (and should) be used to interact with data contained within user defined types. User defined types provide flexibility in the “divide and conquer” scheme in program writing. In other words, one programmer can write a user defined type and guarantee an interface. Another programmer can write the main program with that expected interface. The two pieces are put together and compiled for usage. User defined types provide encapsulation defined in the Object Oriented Programming (OOP) paradigm.

Within classes, to protect the data members, the programmer can define functions to perform the operations on those data members. Member functions and functions are names used interchangeably in reference to classes. Function prototypes are declared within the class definition. These prototypes can take the form of non-class functions as well as class suitable prototypes. Functions can be declared and defined within the class definition. However, most functions can have very large definitions and make the class very unreadable. Therefore it is possible to define the function outside of the class definition using the scope resolution operator “::”. This scope resolution operator allows a programmer to define the functions somewhere else. This can allow the programmer to provide a header file .h defining the class and a .obj file built from the compiled .cpp file which contains the function definitions. This can hide the implementation and prevent tampering. The user would have to define every function again to change the implementation. Functions within classes can access and modify (unless the function is constant) data members without declaring them, because the data members are already declared in the class.

Read also  Richness And Density Of Information Information Technology Essay

Copy constructor:

This constructor takes one argument. Also called one argument constructor. The main use of copy constructor is to initialize the objects while in creation, also used to copy an object. The copy constructor allows the programmer to create a new object from an existing one by initialization. 

For example to invoke a copy constructor the programmer writes:

Exforsys e3(e2); 

or 

Exforsys e3=e2;

Both the above formats can be sued to invoke a copy constructor.

For Example:

#include <iostream.h>

class Exforsys

{

    private:

        int a;

    public:

        Exforsys()

        { }

        Exforsys(int w)

    {

        a=w;

    } 

    Exforsys(Exforsys& e)

    {

        a=e.a;

        cout<<” Example of Copy Constructor”;

    }

    void result()

    {

        cout<< a;

    } 

};

void main()

{

    Exforsys e1(50); 

    Exforsys e3(e1);

    cout<< “ne3=”;e3.result();

}

In the above the copy constructor takes one argument an object of type Exforsys which is passed by reference. The output of the above program is

Example of Copy Constructor

e3=50

the assignment operator or other overloaded operators

The copy assignment operator, often just called the “assignment operator”, is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type. It is one of the special member functions, which means that a default version of it is generated automatically by the compiler if the programmer does not declare one. The default version performs a memberwise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or compiler-generated).

Read also  Full Explanation Of Network Diagram

The copy assignment operator differs from the copy constructor in that it must clean up the data members of the assignment’s target (and correctly handle self-assignment) whereas the copy constructor assigns values to uninitialized data members

Operator New/Delete

In the first newsletter we talked about using C++ as a better C. This term doesn’t have a precise meaning, but one way of looking at it is to focus on the features C++ adds to C, exclusive of the most obvious one, namely the class concept used in object-oriented programming. 

One of these features is operator new and operator delete. These are intended to replace malloc() and free() in the C standard library. To give an example of how these are similar and how they differ, suppose that we want to allocate a 100-long vector of integers for some purpose. In C, we would say: 

int* ip;

ip = (int*)malloc(sizeof(int) * 100);

free((void*)ip);

With new/delete in C++, we would have: 

int* ip;

ip = new int[100];

delete ip;

Inline Functions

Inline functions are best used for small functions such as accessing private data members. The main purpose of these one- or two-line “accessor” functions is to return state information about objects; short functions are sensitive to the overhead of function calls. Longer functions spend proportionately less time in the calling/returning sequence and benefit less from inlining.

http://i.msdn.microsoft.com/Hash/030c41d9079671d09a62d8e2c1db6973.gifExample

The Point class, introduced in Function-Call Results can be optimized as follows:

Copy

// when_to_use_inline_functions.cpp

class Point

{

public:

// Define “accessor” functions as

// reference types.

unsigned& x();

unsigned& y();

private:

unsigned _x;

unsigned _y;

};

inline unsigned& Point::x()

{

return _x;

}

inline unsigned& Point::y()

{

return _y;

}

int main()

{

}

reference variables

c++ references allow you to create a second name for the a variable that you can use to read or modify the original data stored in that variable. While this may not sound appealing at first, what this means is that when you declare a reference and assign it a variable, it will allow you to treat the reference exactly as though it were the original variable for the purpose of accessing and modifying the value of the original variable–even if the second name (the reference) is located within a different scope. This means, for instance, that if you make your function arguments references, and you will effectively have a way to change the original data passed into the function.

Order Now

Order Now

Type of Paper
Subject
Deadline
Number of Pages
(275 words)