Sunteți pe pagina 1din 10

Home Tutorials C++

Class Constructors and destructors in C++


Category: C++
Comments (26) constructor is a member function with the same name as its class. For example:
class X {
public:
X(); // constructor for class X
};

Class Constructors and destructors in C++


In this C++ tutorial you will learn about Class Constructors and destructors in C++
viz., Constructors, What is the use of Constructor, General Syntax of Constructor,
Destructors, What is the use of Destructors and General Syntax of Destructors.

Constructors:
What is the use of Constructor
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:

<class name> { arguments};

The default constructor for a class X has the form

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;
}

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

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()
{ }
}

Definition: A default constructor is a constructor in both C++ and C# that has no parameters
or where it has parameters they are all defaulted.

If no constructor is supplied then the compiler will supply a default constructor. If however,
any kind of constructor is declared by the programmer than a default is not supplied

Inline Functions versus Macros


Although inline functions are similar to macros (because the function code is
expanded at the point of the call at compile time), inline functions are parsed by the
compiler, whereas macros are expanded by the preprocessor. As a result, there are
several important differences:

• Inline functions follow all the protocols of type safety enforced on normal
functions.
• Inline functions are specified using the same syntax as any other function
except that they include the inline keyword in the function declaration.
• Expressions passed as arguments to inline functions are evaluated once. In
some cases, expressions passed as arguments to macros can be evaluated
more than once.

This question was asked in interviews with both Apple and Intuit.
The major difference between inline functions and macros is the way
they are handled. Inline functions are parsed by the compiler, whereas
macros are expanded by the C++ preprocessor. This difference creates
other differences, as best illustrated by examples.

The C++ preprocessor implements macros by using simple text


replacement. Suppose we have the following macro:

Example
The following example shows a macro that converts lowercase letters to uppercase:
Copy
// inline_functions_macro.c
#include <stdio.h>
#include <conio.h>

#define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a))

int main() {
char ch;
printf_s("Enter a character: ");
ch = toupper( getc(stdin) );
printf_s( "%c", ch );
}
Input
xyz
Inline functions remedy the problem previously described.
Copy
// inline_functions_inline.cpp
#include <stdio.h>
#include <conio.h>

inline char toupper( char a ) {


return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a );
}

int main() {
printf_s("Enter a character: ");
char ch = toupper( getc(stdin) );
printf_s( "%c", ch );
}
Input
a
Output
Enter a character: A
Friend Functions
A friend function is a function that is not a member of a class but has access to the
class's private and protected members. Friend functions are not considered class
members; they are normal external functions that are given special access privileges.
Friends are not in the class's scope, and they are not called using the member-
selection operators (. and –>) unless they are members of another class. A friend
function is declared by the class that is granting access. The friend declaration can
be placed anywhere in the class declaration. It is not affected by the access control
keywords.
The following example shows a Point class and a friend function, ChangePrivate.
The friend function has access to the private data member of the Point object it
receives as a parameter.

Example
Copy
// friend_functions.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;


class Point
{
friend void ChangePrivate( Point & );
public:
Point( void ) : m_i(0) {}
void PrintPrivate( void ){cout << m_i << endl; }

private:
int m_i;
};

void ChangePrivate ( Point &i ) { i.m_i++; }

int main()
{
Point sPoint;
sPoint.PrintPrivate();
ChangePrivate(sPoint);
sPoint.PrintPrivate();
}
Output
0
1
Member Functions (C++)
Classes can contain data and functions. These functions are referred to as "member
functions." Any nonstatic function declared inside a class declaration is considered a
member function and is called using the member-selection operators (. and –>).
When calling member functions from other member functions of the same class, the
object and member-selection operator can be omitted. For example:

Copy
// member_functions1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

class Point
{
public:
short x()
{
return _x;
}

short y()
{
return _y;
}

void Show()
{
cout << x() << ", " << y() << "\n";
}
private:
short _x, _y;
};

int main()
{
Point pt;
pt.Show();
}

disadvantage

Answers:

Well if we are talking about the default copy constructor, then the
disadvantage it suffers from is that i does a shallow copy of the
class object.
Which means that if the class has some dynamic memory
allocated or file pointers, the copied object will also point to the
same memory location or files. That is the memory or file is not
copied.

Posted by: Samit Sasan


Contact Samit Sasan

If the programer is defining the copy constructor, the compiler will


invoke the copy constructor at the time of copying the members
of the calling object to the members of the called objects. This will
cretaes the problems if the object contains the pointer variables.
The time copying is more if there are more number of object
memebrs

Posted by: mahendra

Contact mahendra

A copy constructor is called when a new variable is created from


an object. The default copy constructor does a shallow copy i.e;
the copied object points to same old memory pointed by the
parent object. If the object has some dynamic memory or
pointers, it is better to create a copy constructor.

When a new copy constructor is written, assignment operator and


destructor also should be written in the class.

Posted by: suresh

Sponsored Links

C++ Tutorials
• C++ Dereference Operator
• C++ Memory Management operators
• C++ Void Pointer and Null Pointer
• C++ Pointers
• C++ Static Functions
• C++ Friend Functions
• C++ Pure Virtual Function and Base Class
• C++ Virtual Functions
• C++ Polymorphism
• C++ Encapsulation
• C++ Abstraction
• Static Functions - An Introduction
• C++ Inheritance
• Scope of Variables in Function
• C++ Inline Functions
• C++ Function Passing Types
• C++ Storage Classes
• Concept of Function with Arguments
• Concepts of Function
• C++ Operator Overloading Part II
Home Tutorials C++

C++ Encapsulation
Category: C++
Comments (12)

C++ Encapsulation
Introduction
Encapsulation is the process of combining data and functions into a single unit called
class. Using the method of encapsulation, the programmer cannot directly access the
data. Data is only accessible through the functions present inside the class. Data
encapsulation led to the important concept of data hiding. Data hiding is the
implementation details of a class that are hidden from the user. The concept of
restricted access led programmers to write specialized functions or methods for
performing the operations on hidden members of the class. Attention must be paid to
ensure that the class is designed properly.

Neither too much access nor too much control must be placed on the operations in
order to make the class user friendly. Hiding the implementation details and
providing restrictive access leads to the concept of abstract data type. Encapsulation
leads to the concept of data hiding, but the concept of encapsulation must not be
restricted to information hiding. Encapsulation clearly represents the ability to bundle
related data and functionality within a single, autonomous entity called a class.

For instance:

class Exforsys
{
public:
int sample();
int example(char *se)
int endfunc();
.........
......... //Other member functions

private:
int x;
float sq;
..........
......... //Other data members
};

In the above example, the data members integer x, float sq and other data members
and member functions sample(),example(char* se),endfunc() and other member
functions are bundled and put inside a single autonomous entity called class
Exforsys. This exemplifies the concept of Encapsulation. This special feature is
available in object-oriented language C++ but not available in procedural language
C. There are advantages of using this encapsulated approach in C++. One advantage
is that it reduces human errors. The data and functions bundled inside the class take
total control of maintenance and thus human errors are reduced. It is clear from the
above example that the encapsulated objects act as a black box for other parts of
the program through interaction. Although encapsulated objects provide
functionality, the calling objects will not know the implementation details. This
enhances the security of the application.

The key strength behind Data Encapsulation in C++ is that the keywords or the
access specifiers can be placed in the class declaration as public, protected or
private. A class placed after the keyword public is accessible to all the users of the
class. The elements placed after the keyword private are accessible only to the
methods of the class. In between the public and the private access specifiers, there
exists the protected access specifier. Elements placed after the keyword protected
are accessible only to the methods of the class or classes derived from that class.

The concept of encapsulation shows that a non-member function cannot access an


object's private or protected data. This adds security, but in some cases the
programmer might require an unrelated function to operate on an object of two
different classes. The programmer is then able to utilize the concept of friend
functions. Encapsulation alone is a powerful feature that leads to information hiding,
abstract data type and friend functions.

Features and Advantages of the concept of Encapsulation:


* Makes Maintenance of Application Easier:

Complex and critical applications are difficult to maintain. The cost associated with
maintaining the application is higher than that of developing the application properly.
To resolve this maintenance difficulty, the object-oriented programming language C+
+ created the concept of encapsulation which bundles data and related functions
together as a unit called class. Thus, making maintenance much easier on the class
level.

* Improves the Understandability of the Application

* Enhanced Security:

There are numerous reasons for the enhancement of security using the concept of
Encapsulation in C++. The access specifier acts as the key strength behind the
concept of security and provides access to members of class as needed by users.
This prevents unauthorized access. If an application needs to be extended or
customized in later stages of development, the task of adding new functions
becomes easier without breaking existing code or applications, there by giving an
additional security to existing application.

S-ar putea să vă placă și