Академический Документы
Профессиональный Документы
Культура Документы
C++ Programming features - Data Abstraction - Encapsulation - class - object constructors static members constant members member functions pointers
references - Role of this pointer Storage classes function as arguments.
Data abstraction refers to, providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in program
without presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation
of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs,
and DVD players, BUT you do not know its internal details, that is, you do not know
how it receives signals over the air or through a cable, how it translates them, and finally
displays them on the screen.
Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having zero knowledge of its internals.
Now, if we talk in terms of C++ Programming, C++ classes provides great level of
data abstraction. They provide sufficient public methods to the outside world to play
with the functionality of the object and to manipulate object data, i.e., state without
actually knowing how class has been implemented internally.
In C++, we use classes to define our own abstract data types (ADT). You can use the
cout object of class ostream to stream data to standard output like this:
#include <iostream.h>
int main( )
{
cout << "Hello C++" <<endl;
return 0;
}
Here, you don't need to understand how cout displays the text on the user's screen.
You need to only know the public interface and the underlying implementation of
cout is free to change.
In C++, we use access labels to define the abstract interface to the class. A class may
contain zero or more access labels:
Members defined with a public label are accessible to all parts of the program. The
data-abstraction view of a type is defined by its public members.
Members defined with a private label are not accessible to code that uses the class.
The private sections hide the implementation from code that uses the type.
There are no restrictions on how often an access label may appear. Each access label
specifies the access level of the succeeding member definitions. The specified access
level remains in effect until the next access label is encountered or the closing right
brace of the class body is seen.
Class internals are protected from inadvertent user-level errors, which might corrupt
the state of the object.
The class implementation may evolve over time in response to changing requirements
or bug reports without requiring change in user-level code.
By defining data members only in the private section of the class, the class author is
free to make changes in the data. If the implementation changes, only the class code
needs to be examined to see what affect the change may have. If data are public, then
any function that directly accesses the data members of the old representation might
be broken.
Any C++ program where you implement a class with public and private members is
an example of data abstraction. Consider the following example:
#include <iostream.h>
using namespace std;
class Adder
{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result: Total 60
Above class adds numbers together, and returns the sum. The public members
addNum and getTotal are the interfaces to the outside world and a user needs to
know them to use the class. The private member total is something that the user
doesn't need to know about, but is needed for the class to operate properly.
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can contain
private, protected and public members. By default, all items defined in a class are
private.
For example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your
program. This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you
must declare them after the public keyword. All variables or functions defined after
the public specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all
other classes as possible.
#include <iostream.h>
#include<conio.h>
class Adder
{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
When the above code is compiled and executed, it produces the following result: Total 60
Above class adds numbers together, and returns the sum. The public member s
addNum and getTotal are the interfaces to the outside world and a user needs to know them
to use the class. The private member total is something that is hidden from the outside world,
but is needed for the class to operate properly.
Designing Strategy:
Most of us have learned through bitter experience to make class members private by
default unless we really need to expose them. That's just good encapsulation.
This wisdom is applied most frequently to data members, but it applies equally to all
members, including virtual functions.
1.4 CLASS:
In oop, class is a user defined data type that can hold data and their associated functions
into single unit.
The class members are divided into two types:
1. Data Member
2. Function Member
In class there are certain privilege for accessing both data and function members.
They are said to be access specifiers.
It is divided into three categories. They are,
1.Public
2.private
3.Protected
By default the data members are private. So the private members of a class are not
accessible from outside the class. If the data members are specified as public then the
members of a class can be accessible from inside and outside of the class.
Syntax of a class
class class_name
{
Access Specifier:
Data Members
Access Specifier:
Function Members
};
Example:
Consider an example of class
class student
{
public:
int rollno,age;
Data Members
char *name;
void getdetail()
{
Cin>>rollno>>age;
Cin>>name;
}
Function Members
void printdetail()
{
Cout<<rollno<<age;
Cout<<name;
}
};
In this example a class named student with data members such rollno, age and name
and with function members getdetail() and printdetail() is defined within the class.The access
specifiers of this class is public.
Return type specifies the type of a function. Class name specifies the name of a class
in which the function belongs. The operator:: denotes scope resolution operator. Function name
specifies the name of a function.
Example:
class student
{
public:
int rollno,age;
char *name;
void getdetail();
void printdetail();
};
void student::getdetail()
{
Cin>>rollno>>age;
Cin>>name;
}
void student::printdetail()
{
Cout<<rollno<<age;
Cout<<name;
}
1.5 OBJECTS:
Objects are the variables of user defined data type called class. Once a Class has been
created we can declare any number of variables belongs to that class. In the above example
class student we can declare any number of variables of class student in the main function.
Using objects we can access any public members of a class using Dot Operator.
Syntax:
Class_Name object1, object2, object3.object n;
void main ()
{
class Name
s1.getdetail (); Object s1 access (call) the function member getdetail () of student class
s1.printdetail ();
Class student
Function Members:
Void getdetail()
Void printdetail()
Object s1:
Object s2:
Object s3:
1.6 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
A constructor is a special member function that takes the same name as the class
name. The default constructor for a class X has the form
X::X()
In the above example, the arguments are 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. The default Constructor is also called as the
no argument constructor.
For example:
class Exforsys
{
private:
int a,b;
public:
Exforsys();
...
};
Exforsys :: Exforsys()
{
a=0;
b=0;
}
Parameterized Constructor:
A default constructor does not have any parameter, but if you need, a constructor
can have parameters. This helps you to assign initial value to an object at the time of its creation
as shown in the following example:
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6
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>
using namespace std;
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();
}
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.
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.
For example:
class Exforsys
{
private:
...
public:
Exforsys()
{
}
~ Exforsys()
{
}
}
Example Program:
#include<iostream.h>
#include<conio.h>
class count
{
public:
static int countt;
void dispcount()
{ countt++;
cout<<"Object\t"<<countt<<"\n";
}
};
int count::countt;
void main()
{
count c1,c2,c3,c4,c5;
clrscr();
c1.dispcount();
c2.dispcount();
c3.dispcount();
c4.dispcount();
c5.dispcount();
getch();
}
In this example class count has a static data member countt.This program is used for
counting the number of objects which is declared in the class.So when an object c1 access the
function dispcount() the static variable has the value 1.when s5 access the function the value
will be incremented to 5.
Output:
Object 1
Object 2
Object 3
Object 4
Object 5
NOTE:
Once the static data member is defined it is automatically initialized to zero.
Initially the value for the data members is set by constructor during the object
creation.
Constant objects can access only the constant member function .The constant function
is read only function it cannot alter the value of object data members
{
//read only function
}
};
void main()
{
const class_name object( parameter);
//constant objects
Ex:
void printdetails() const
{
cout<<Roll No is:<<rollno;
cout<<Name is:<<name;
cout<<Address is:<<address;
rollno=10; / / the following line is erroneous
}
//it is allowed
{
cout<<"Time is:"<<hour<<"Hour:\t"<<minute<<"Minutes:\t"<<second<<"Seconds:\n";
}
~time()
{
}
void get() const
{
cin>>hour>>minute>>second;
}
};
void main()
{
clrscr();
const time t1(8,55,50);
//Constant objects
t1.disp();
t1.get();
t1.disp();
getch();
}
Output
Time is:8Hour: 55Minutes:
50Seconds:
5
50
40
Time is:8Hour: 55Minutes:
50Seconds:
In this example, the object of this time class is set with the default value of 8 hour 55
minutes and 50 seconds and it is initialized with constructor. Since this object t1 is a n
constant object it cannot be modified and it can access only the constant function in a class.
Syntax
class stat
{
static return_type function_name()
{
Statement;
}
};
Calling Static Function in the main Function
void main()
{
class_name::static function name();
}
Example:
#include<iostream.h>
#include<conio.h>
class count
{
public:
static int countt;
count()
{ countt++;
cout<<"Object\t"<<countt<<"\n";
}
static void statfun()
{
cout<<"Object\t"<<countt<<"\n";
}
};
int count::countt;
void main()
{
count c1,c2,c3,c4,c5;
clrscr();
count::statfun();//calling the constructor using classname
getch();//scope resolution operator and the static funtion name
}
Output:
Object 5
The programmer must note the following while using static member functions:
A static member function can only access static member data, static member functions
and data and functions outside the class. The programmer must take note not to use
static member function in the same manner as non-static member function, as non- static
member function can access all of the above including the static data member.
A non-static member function can be declared as virtual but care must be taken not to
declare a static member function as virtual.
The programmer must first understand the concept of static data while learning the
context of static functions. It is possible to declare a data member of a class as static
irrespective of it being a public or a private type in class definition. If a data is
declared as static, then the static data is created and initialized only once. Non-static
data members are created again and again. For each separate object of the class, the
static data is created and initialized only once. As in the concept of static data, all objects
of the class in static functions share the variables. This applies to all objects of the class.
A non-static member function can be called only after instantiating the class as an
object. This is not the case with static member functions. A static member function
can be called, even when a class is not instantiated.
A static member function cannot have access to the 'this' pointer of the class.
1.10 POINTERS:
Every storage location of memory has an associated address. The address is a number
that grows sequentially. For every program placed in memory, each variable or function in
the program has an associated address.
For Example
#include <iostream>
using namespace std;
void main()
{
int exf=200;
int test=300;
cout << endl << &exf << endl << &test;
}
The &exf has the address associated with the integer variable exf and the &test has
the address associated with the integer variable test which are displayed using the cout
statement.
Using the understanding of address of operators, the discussion turns to the concept of
pointers.
exforsys = 100;
test = exforsys;
x = &exforsys;
Using the above information, the assignment takes place as below:
exforsys is an integer variable having the value of 100 stored in memory address location
3501.
When the variable exforsys is assigned to the variable test in the second statement:
test = exforsys;
The value of the variable exforsys 100 is copied to the variable test.
In the third statement, the address of the variable exforsys is denoted by reference operator
&exforsys is assigned to the variable x as:
x = &exforsys;
The address of the variable 3501 and not the contents of the variable exforsys is
copied into the variable x. The pointers concept fits in this statement. Pointers are the
variables that store the reference to another variable. Pointers are variables that store the address
of the variable that it is pointed by. Variable x is referred to as the pointer in the above
example.
The programmer must note that the address operator placed before a variable is not
the same as operator & placed after the variable. For example, &x is not same as x&.
Variable &x refers to address operator whereas x& refer to reference operator&. Pointer is a
variable that holds the address, also called pointer variable.
1.11 REFERENCES:
A reference variable is an alias, that is, another name for an already existing variable.
Once a reference is initialized with a variable, either the variable name or the reference name
may be used to refer to the variable.
i = 17;
Read the & in these declarations as reference. Thus, read the first declaration as "r is
an integer reference initialized to i" and read the second declaration as "s is a double
reference initialized to d.". Following example makes use of references on int and double:
#include <iostream.h>
int main ()
{
// declare simple variables
int
i;
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
When the above code is compiled together and executed, it produces the following result:
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
References are usually used for function argument lists and function return values. So
following are two important subjects related to C++ references which should be clear to a
C++ programmer: we can implement call by reference concept using pointers.
Here is another example of call by reference which makes use of C++ reference:
#include <iostream.h>
// function declaration
void swap(int& x, int& y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
return 0;
}
/* put y into x */
return;
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
Example:
#include <iostream.h>
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
Automatic:
Variables defined within the function body are called automatic variables. Auto is the
keyword used to declare automatic variables. By default and without the use of a keyword,
the variables defined inside a function are automatic variables.
For instance:
void exforsys( )
{
auto int x;
auto float y;
...
}
is the same as
void exforsys( )
{
int x;
float y;
//Automatic Variables
...
}
In the above function, the variable x and y are created only when the function
exforsys( ) is called. An automatic variable is created only when the function is called. When
the function exforsys( ) is called, the variables x and y are allocated memory automatically.
External:
External variables are also called global variables. External variables are defined outside
any function, memory is set aside once it has been declared and remains until the end of the
program. These variables are accessible by any function. This is mainly utilized when a
programmer wants to make use of a variable and access the variable among different function
calls.
Static:
The static automatic variables, as with local variables, are accessible only within the
function in which it is defined. Static automatic variables exist until the program ends in the
same manner as external variables. In order to maintain value between function calls, the
static variable takes its presence.
For example:
#include <iostream.h>
using namespace std;
int exforsys(int);
int exforsys2(int);
void main( )
{
int in;
int out;
while(1)
{
address. Function pointers can be used to simplify code by providing a simple way to select a
function to execute based on run-time values.
#include <iostream.h>
int add(int first, int second)
{
return first + second;
}
int subtract(int first, int second)
{
return first - second;
}
int operation(int first, int second, int (*functocall)(int, int))
{
return (*functocall)(first, second);
}
void main()
{
int a, b;
int (*plus)(int, int) = add;
int (*minus)(int, int) = subtract;
a = operation(7, 5, plus);
b = operation(20, a, minus);
cout << "a = " << a << " and b = " << b << endl;
}