Sie sind auf Seite 1von 12

Default Argument

C++ allows us to call a function without specifying all its arguments. In such cases the
function assign a default value to the parameter which does not have a matching
argument in the function call. Default values are specified when the function is declared.

sum(int a, int b, int c)


{

sum();

Function Overloading

Overloading refers to the use of the same thing for different purposes. This means that we
can use the same function name to create functions that perform a variety of different
tasks. This is known as function polymorphism in OOP's. We can design a family of
functions with one function name but with different argument lists. The function would
perform different operations depending on the argument list in the function call. The
correct function to be invoked is dertermined by checking the number and type of the
arguments, but not on the function type.

Features of Object Oriented Programming

1. Encapsulation
2. Inheritance
3. Polymorphism

1. Encapsulation :

The wrapping of data and function into a single unit is known as Encapsulation. Data is
not accessible externally and is accessible to only those functions, which are wrapped in
the class can access it. These functions provide the interface between the data and
program. Encapsulation of data from direct access by the program is called Data Hiding.

Class & Objects

Limitations of C strucutre

An important limitation of C structure is that they do not permit data hiding. Strucutre
members can be directly accessed by the structure variable by any function anywhere in
their scope.

1
Class

A class is a way to bind the data and its associated functions together. It allows the data
and functions to be hidden if necessary from external user. When defining a class we are
creating a new abstract data type that can be treated like any other built in data type.

A class specification has two parts:

1. Class declaration 2. Class function definition

syntax of class

class class-name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
}

The class declaration is similar to a struct declaration. The class body contains the
declaration of variables and functions. These functions and variables are called members.
They are usually grouped into two sections private and public. The keywords private and
public are known as Visibility Labels. They are followed by a colon (:)

The members that have been declared as private can be accessed only from within the
class. On the other hand public members can be accessed from outside the class also.
The data hiding is done using private declarations. The use of private keyword is optional.
If both the keywords are missing then by default all the members are private. Only the
member functions can have access to the private data members (both variable and
functions). However, the public members (both variable and functions) can be accessed
from outside the class.

The binding of both data and function together into single class type variable is referred to
as Encapsulation.

Q. Write a program to store details of student like rollno,name and marks of three
subjects. Write necessary functions to store the data and display the data. Also calculate
the total marks obtained. Display Rollno,Name and Total Marks. Keep the data members
as private.

Instances :

2
When we have more than one object for a class then it is called as instances of a class.

class xyz
{
int a,b,c;
};

void main()
{
xyz x1,x2,x3;

Scope Resolution Operator(::)

Like C, C++ is also a block structured language. Blocks and scopes can be used in
constructing programs. We know that same variable name can be used to have different
meanings in different blocks. The scope of the variable extends from the point of its
declaration till the end of the block containing the declarations. A variable declared inside
a block is said to be local to that block.

In C, the global version of a variable cannot be accessed from the inner block. C++
resolves this problem by introducing a new operator (::) called the scope resolution
operator. This can be used to uncover a hidden variable. This operator allows access to
the global version of a variable.

Static Data Members

A data member of a class can be qualified as static. The properties of a static member
variable are similar to that of a C static variable. A static member variable has certain
special characteristics.

1. It is initialized to zero when the first object of its class is created. No other initialization is
permitted

2. Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.

3. It is visible only within the class, but its lifetime is the entire program.

Note:

The type and scope of each static member variable must be defined outside the class
definition. This is necessary because the static data members are stored separately rather

3
than as a part of an object. Since they are associated with the class, itself rather than with
any class object they are also called class variables.

syntax

<data type> <name of class>::<static variable name>;

a b
t1 1 6
t2 3
t3 5

Static member functions

Like static member variables, we can also have static member functions. A member
function that is declared has the following properties:

1. A static function can have access to only other static members(functions or variables)
declared in the same class.

2. A static function can be called using the class name (instead of its object) as follows:

class-name :: function name;

void main()
{
struct emp
{
int empno;
char name[20];
}s;

disp(s)

disp(struct emp e)
{

Friend Function

4
We know that private members cannot be accessed from outside the class. That is non-
member function cannot have an access to the private data of a class. To make an
outside function "friendly" to a class we have to simply declare this function as a friend of
the class. The function that are declared with the keyword friend is known as friend
function. A function can be declared as friend in any number of classes. A friend function,
although not a member function has full access rights to the private members of the class.

A friend function possesses certain special characteristics:

1. It is not in the scope of the class to which it has been declared as friend.

2. Since it is not in the scope of the class it cannot be called using the object of that class.
It can be invoked like a normal function without the help of any object.

3. Unlike member functions, it cannot access the member names directly and has to use
an object name and dot membership operator with each member name.

4. Usually, it has the objects as arguments.

Constructor

We have seen so far a few examples of classes being implemented. In all the cases, we
have used member functions such as setdata() or getdata() to intialize the values of class
variables.

All these function call statements are used to initialize the member variables at the time of
creation of their objects.

One of the aim of C++ is to create user - defined data types. C++ provides a special
member function called the CONSTRUCTOR which enables an object to initialize itself
when it is created. This is known as automatic initialization of objects.

A constructor is a special member function whose task is to initialize the objects of its
class. It is special because its name is the same as the class name. The constructor is
invoked whenever an object of its associated class is created. It is called constructor
because it construct the values of data members of the class.

Characteristics of Constructor function

1. They should be declared in the public section.

2. They are invoked automatically when the objects are created.

3. They do not have return type, not even void and therefore they cannot return values.

5
4. They cannot be inherited, though a derived class can call the base class constructors.

Copy Constructor

A copy constructor is used to declare and initialize an object from another object. A copy
constructor takes a reference to an object of the same class as itself as an argument.

Destructors

A destructor is used to destroy the objects that have been created by a constructor. Like a
constructor, the destructor is a member function whose name is the same as the class
name but is preceded by tilde (~) sign. A destructor never takes any argument nor does it
return any value. It will be invoked implicitly by the compiler upon exit from the program (or
block or function) as the case may be to clean up storage that is no longer accessible. It is
good practice to declare destructors in a program since it releases memory space for
future use.

2. Inheritance :

Reusability is yet another important feature of OOP's. It is always nice if we could reuse
something that already exists rather than trying to create the same all over again.

C++ supports the concept of reusability. The C++ classes can be reused in several ways.
Once a class has been written and tested, it can be adapted by other programs to suit
their requirements. This is basically done by creating new classes, reusing the properties
of the exisiting ones. The mechanism of deriving a new class from an old one is called
Inheritance. The old class is referred to as the Base class and the new one is called the
derived class.

The derived class inherits some or all of the properties from the base class.

syntax

class derived-class name : <visibility mode> Base-class-name


{

};

When a base class is privately inherited by a derived class, public members of the base
class become private members of the derived class and therefore the public members of
the base class can only be accessed by the member functions of the derived class. They
are inaccessible to the objects of the derived class.

6
On the other hand when the class is publicly inherited, public members of the base class
become public members of the derived class and therefore they are accessible to the
objects of the derived class. In both the cases, the private members are not inherited and
the private members of a base class will never become the members of its derived class.

class A Base class


{

class B : public A Derived class


{

Single Inheritance : when we have only one base class for a derived class it is called as
single inheritance

Base class A

Derived class B

Making the private member inheritable

We have seen that a private member of a base class cannot be inherited and therefore it
is not accessible for the derived class directly. What do we do if the private data needs to
be inherited by a derived class?

Protected

C++ provides a third visibility label called protected, which serve a limited purpose in
inheritance. A member declared as protected is accessible by the member function within
its class and any class immediately derived from it. It cannot be accessed by the function
outside these two classes.

When a protected member is inherited in public mode, it becomes protected in the derived
class too, and therefore is accessible by the member functions of the derived class. It is
also ready for further inheritance.

When a protected member, inherited in the private mode derivation, becomes private in
the derived class. Although it is available to the member functions of the derived class, it is
not available for further inheritance (since private members cannot be inherited).

7
Multiple Inheritance

When a derived class has more than one base class it is called as multiple inheritance.

student Marks

Result

Multilevel Inheritance

A class is derived from another derived class. The class A serves as a base class for the
derived class B which in turn serves as a base class for the derived Class C. The class B
is known as intermediate base class since it provides a link for the inheritance between A
and C. ABC is known as inheritance path.

Base class A Grandfather

Intermediate B Father
Base class

Derived class C Child

Hybrid Inheritance

There could be situtation where we need to apply two or more types of inheritance to
design a program. For instance, consider the case of processing the students result.
Assume that we have to give weightage for sports before finalizing the results. The
weightage for sports is stored in a separate class called sports. The result will have both
multilevel and multiple inhertiance.

Multipath Inheritance

Consider a situation where a child has two direct base classes "Parent1"
and "Parent2", which themseleves have a common base class "Grandparent". The "Child"
inherits the properties of "Grandparent" via two separate paths. It can also inherit directly
from the grandparent. The grandparent is sometimes reffered to as indirect base class.
Inheritance by the "Child" might pose some problems. All the public and protected
members of "Grandparent" are inherited into "Child" twice first via "Parent1" and again via
"Parent2". This means child will have duplicate sets of the membrs inherited from
grandparent. This introduces ambiguity and should be avoided.

The duplication of inherited members due to these multiple paths can be avoided by
making the common base class (ancestor class) as virtual base class while declaring the
direct or intermediate base classes.

8
When a class is made a virtual base class C++ makes necessary care to see that only
one copy of the class is inherited.

Pointers and classes

As you know pointer is a variable which holds the memory address of variable of any data
type such as int, float or sometimes an array. Even pointer variable can hold the address
of the class object. The pointer to an object of class variable will be accessed and
processed in one of the following ways:

1. (*object name).member-name;
2. object-name->member-name;

Union and class

A union is a user defined data type whose size is sufficient to contain one of its members.
At most, one of the members can be stored in a union at any time. A union is also used for
declaring classes in C++. The members of a union are public by default. A union allows to
store its members only one at a time. A union may have member functions including
constructors and destructors but not virtual functions. A union may not have a base class.
A union can have no static data member.

Nested Class

C++ permits declaration of a class within another class. A class declared as member of
another class is called as a nested class or a class within another class.

Virtual Function

When we use the same function name in both the base class and derived class, the
function in base class is declared as virtual using the keyword virtual preceeding its
normal declaration. When a function is made virtual, C++ determines which function to
use at run time based on the type of object pointed to by the base pointer, rather than the
type of the pointer.

Pure Virtual Function

It is a normal practice to declare a function virtual inside the base class and redifine it in
the derived class. Such functions are called "do-nothing" functions. Such functions are
called Pure Virtual Functions.

9
A pure virtual function is a function declared in a base class that has no definition relative
to the base class. In such cases the compiler requires each derived class to either define
the function or redeclare it as a pure virtual function. Remember that a class containing
pure virtual function cannot be used to declare any objects of its own. Such classes are
called abstract classes.

Templates

A template can be used to create a family of classes or functions. With a template, it is


possible to create generic functions and generic classes.

Generic functions:

In a generic function the type of data upon which the function operates is specified as a
parameter. This function with several different types of data without having to explicitly
recode for different data types.

Generic Class:

In the generic class, the actual type of the data being manipulated will be specified as a
parameter when objects of the class are created.

Random Files

Updating is a routine task in the maintanence of any data file. The updating would include
one or more of the following tasks:

1. Displaying the content of a file


2. Modifying the existing item
3. Add a new item

These actions require the file pointers to move to a particular location that corresponds to
the item/object under consideration. This can be easily implemented if the file contains a
collection of items/object of equal length. In such cases, the size of each object can be
obtained using the statement

int object_length=sizeof(object);

Then, the location of a desired object, say the mth object may be obtained as follows:

int location = m - 1 * object_length;

The location gives the byte number of the first byte of the mth object. Now we can set the
file pointer to reach this byte with the help of seekg() or seekp().

10
We can also find out the total number of objects in a file using the object_length as
follows:

int n=file_size/object_length;

The file size can be obtained using the function tellg() or tellp() when the file pointer is
located at the end of the file.

Inline Function

the obejctive of using functions in a program is to save some memory space, which
becomes appreciable when a function is likely to be called many times. However every
time a function is called, it takes a lot of extra time in executing a series of instructions for
tasks such as jumping to the function, saving registers, pushing arguments into the stack
and returning to the calling function. When a function is small, a large percentage of
execution time may be spent in such overheads.

C++ has a different solution to this problem. To eliminate the cost of calls to small
functions, C++ proposes a new function called inline function. An inline function is a
function that is expanded in line when it is invoked. That is, the compiler replaces the
function call with the corresponding function code.

We should exercise care before making a function inline. The speed benefits of inline
function diminish as the function grows in size.

Remember that the inline keyword merely sends a request, not a command, to the
compiler. The compiler may ignore this request if the function definition is too long or to
complicated and compile the function as a normal function.

Dynamic Memory Allocations

Two operators namely new and delete are used in dynamic memory allocations.

1. new - The new operator is used to create a heap of memory space for an object of a
class. In C, there are special functions used to create a memory space dynamically, like
malloc(). C++ provides a new way in which dynamic memory is allocated. In reality, the
new keyword calls upon the function operator new() to obtain storage.

An allocation expression must carry out the following three things

1. Find storage for the object to be created


2. Initialize that object
3. Return a suitable pointer type to the object.

11
The new operator returns a pointer to the object created.

syntax

int *p = new int;


data_type pointer = new data_type;

where data_type can be short, int, float, char, array or even class objects.

2. delete - The delete operator is used to destroy the variable space which has been
created by using the new operator dynamically. It is similar to the function free() in C. The
delete keyword calls upon the function operator delete() to release storage which was
created using the new operator.

syntax

delete *p;
delete pointer;

Note that delete operator is used for only releasing the heap memory space which was
allocated by the new operator.

12

Das könnte Ihnen auch gefallen