c++ _unit_1
TRANSCRIPT
-
7/29/2019 c++ _UNIT_1
1/60
ORIGINOF C++
Invented by Bjarne Stroustrup .
1980C with Classes .
1983/1984C with Classes redesigned and renamed C++.
Overcame several shortcomings of C.
Incorporated object oriented programmingC remains a subset of C++
-
7/29/2019 c++ _UNIT_1
2/60
Object-Oriented programmingIdentification of objects to be modeled.Concentrate on what an object does.
Hide how an object performs its tasks.
Identify an objects behavior and attributes.
Encapsulation :The mechanism that binds together code and the data itmanipulates & keeps both safe outside interference andmisuse
Polymorphism:
It is the quality that allows one name to used for 2 or morerelated but technically different purposes.
Inheritance:It is the Process by which one object can acquire theproperties of another.
-
7/29/2019 c++ _UNIT_1
3/60
FUNDAMENTALS OF C++
Object-Oriented Programming language
Pass-by-reference
Operator overloading
Generic programming (templates)Exception handling
Namespaces
Default arguments
-
7/29/2019 c++ _UNIT_1
4/60
A SAMPLE C++ PROGRAM
#include
using namespace std;
int main()
{
int i;
cout >
cout > i;
// now, output a number using
-
7/29/2019 c++ _UNIT_1
5/60
A CLOSER LOOKATTHE I/O OPERATORS
#include
using namespace std;
int main()
{
float f; char str[80];
double d;
cout > f >> d;
cout > str;
cout
-
7/29/2019 c++ _UNIT_1
6/60
DECLARING LOCAL VARIABLES
/* Incorrect in C. OK in C++. */
int f()
{
int i; i = 10;
int j; /* won't compile as a C program */
j = i*2;
return j;
}
-
7/29/2019 c++ _UNIT_1
7/60
THEPROGRAMFROMTHEPRECEDINGSECTION
DECLARESEACHVARIABLEJUSTBEFOREITIS
NEEDED.
#include
using namespace std;
int main()
{
float f; double d; cout > f >> d;
cout > str; cout
-
7/29/2019 c++ _UNIT_1
8/60
OLD-STYLEVS. MODERN C++
/*An old-style C++ program.*/
#include
int main()
{
return 0; }
/*A modern-style C++ program that uses
the new-style headers and a namespace.*/
#include
using namespace std; int main()
{
return 0;
}
-
7/29/2019 c++ _UNIT_1
9/60
THE NEW C++ HEADERS
Standard C++ created a new kind of header that isused by the Standard C++ library.
The new-style headers do not specify filenames.
Instead, they simplyspecify standard identifiers that
may be mapped to files by the compiler, althoughthey need not be.
The new-style C++ headers are an abstraction thatsimply guarantee that the appropriate prototypes
and definitions required by the C++ library havebeen declared
Since the new-style headers are not filenames, theydo not have a .h extension
-
7/29/2019 c++ _UNIT_1
10/60
NAMESPACES
When you include a new-style header in your
program, the contents of that header are contained
in the std namespace.
A namespace is simply a declarative region.
Thepurpose of a namespace is to localize thenames of identifiers to avoid name collisions.
using namespace std;
It can be used to bring the std name space intovisibility
-
7/29/2019 c++ _UNIT_1
11/60
INTRODUCING C++ CLASSESClassis a user defined data type just like structures, but with a difference.
It also has three sections namely private, publicand protected.
Using these, access to member variables of a class can be strictlycontrolled.
Conventions for naming classesShould be meaningful
Should ideally be a noun
First letter of every word should be in upper case
Rules for naming classes
Must not contain any embedded space or symbol
Must begin with a letter, which may be followed by a sequence of letters ordigits
Cannot be a keyword
-
7/29/2019 c++ _UNIT_1
12/60
The following is the general format of defining a classtemplate:
class class_name
{
public : // Must
type member_variable_name;
:type member_function_name();
:
private: // Optional
type member_variable_name;
:type member_function_name();
:
};
-
7/29/2019 c++ _UNIT_1
13/60
The keyword classis used to define a class template.
The private and public sections of a class are given by
the keywords private and publicrespectively.
Determine the accessibility of the members. All the
variables declared in the class, whether in the private or
the public section, are the members of the class.
The class scope is private by default.
-
7/29/2019 c++ _UNIT_1
14/60
#include
using namespace std;
#define SIZE 100
// This creates the class stack. class stack
{ int stck[SIZE];
int tos;
public: void init();
void push(int i);
int pop();
};
void stack::init()
{ tos = 0;
}
-
7/29/2019 c++ _UNIT_1
15/60
void stack::push(int i)
{ if(tos==SIZE)
{ cout
-
7/29/2019 c++ _UNIT_1
16/60
int main()
{ stack stack1, stack2; // create two stack objects
stack1.init();
stack2.init();
stack1.push(1);
stack2.push(2);
stack1.push(3);
stack2.push(4);
cout
-
7/29/2019 c++ _UNIT_1
17/60
Function Overloading C++ achieves polymorphism is through the use of
function overloading. It is the process of using the same name for two or
more functions
Requires each redefinition of a function to use a
different function signature that is: different types of parameters,
or sequence of parameters,
or number of parameters
Is used so that a programmer does not have to
remember multiple function names
-
7/29/2019 c++ _UNIT_1
18/60
#include
using namespace std;
// abs is overloaded three ways int abs(int i);
double abs(double d);
long abs(long l);
int main()
{
cout
-
7/29/2019 c++ _UNIT_1
19/60
int abs(int i)
{ cout
-
7/29/2019 c++ _UNIT_1
20/60
Operator Overloading To make operations on a user-defined data type as
simple as the operations on a built-in data type. Operator Overloading is one form ofPolymorphism,an
important feature of object-oriented programming .
Polymorphism means one thing having many forms, i.e.
here an operator can be overloaded to perform differentoperations on different data types on different contexts.
Operator Overloading is also called operational
polymorphism.
Another form of polymorphism is function overloading.
-
7/29/2019 c++ _UNIT_1
21/60
INHERITANCE
Inheritance means deriving new classes from the
old ones.
The old class is called the base classorparentclass or super classand the class which is derivedfrom this base class is called as derived classorchild class or sub class.
Deriving a new class from an existing one , allows
redefining a member function of the base class and
also adding new members to the derived class .
-
7/29/2019 c++ _UNIT_1
22/60
TYPESOFINHERITANCE
1.Multilevel inheritanceIn multilevel inheritance there is a parent class , from
whom we derive another class .
from this derived class we can derive another class and
so on.
-
7/29/2019 c++ _UNIT_1
23/60
2.Multiple Inheritance
Multiple inheritance , as the name suggests , is
deriving a class from more than one class . The derived class inherits all the properties of all its
base classes.
Consider the following example :
-
7/29/2019 c++ _UNIT_1
24/60
3.Hybrid Inheritance
There are many combinations in which inheritance
can be put to use. For instance, inheriting a classfrom two different classes, which in turn have been
derived from the same base class .
-
7/29/2019 c++ _UNIT_1
25/60
the building class is declared.
It will serve as the base for two derived classes.
class building {
int rooms;
int floors;
int area;
public:
void set_rooms(int num);
int get_rooms();
void set_floors(int num);
int get_floors(); void set_area(int num);
int get_area();
};
-
7/29/2019 c++ _UNIT_1
26/60
BUILDINGISINHERITED
here is a derived class called house:
// house is derived from building
class house : public building
{
int bedrooms;
int baths;
public: void set_bedrooms(int num);
int get_bedrooms(); void set_baths(int num);
int get_baths();
};
-
7/29/2019 c++ _UNIT_1
27/60
The general form for inheritance is
class derived-class : access base-class
{
// body of new class
}
Here, access is optional
-
7/29/2019 c++ _UNIT_1
28/60
ITCREATESTWODERIVEDCLASSESOFBUILDINGUSINGINHERITANCE; ONEISHOUSE, THEOTHER,SCHOOL.
#include
using namespace std;
class building
{ int rooms;
int floors;
int area;
public: void set_rooms(int num);
int get_rooms();
void set_floors(int num); int get_floors();
void set_area(int num);
int get_area();
};
-
7/29/2019 c++ _UNIT_1
29/60
// house is derived from building
class house : public building
{ int bedrooms;
int baths;
public:
void set_bedrooms(int num);
int get_bedrooms();
void set_baths(int num);
int get_baths();
};
// school is also derived from building class school : public building
{ int classrooms;
int offices;
public:
void set_classrooms(int num); int get_classrooms();
void set_offices(int num);
int get_offices();
};
-
7/29/2019 c++ _UNIT_1
30/60
void building::set_rooms(int num)
{ rooms = num;
}
void building::set_floors(int num)
{ floors = num;
}
void building::set_area(int num)
{ area = num;
} int building::get_rooms()
{ return rooms;
}
int building::get_floors()
{ return floors;
}
int building::get_area()
{ return area;
}
-
7/29/2019 c++ _UNIT_1
31/60
void house::set_bedrooms(int num)
{ bedrooms = num;
} void house::set_baths(int num)
{ baths = num;
} int house::get_bedrooms()
{ return bedrooms;
}
int house::get_baths()
{ return baths;
}
-
7/29/2019 c++ _UNIT_1
32/60
void school::set_classrooms(int num)
{ classrooms = num;
}
void school::set_offices(int num)
{ offices = num;
}
int school::get_classrooms() {
return classrooms;
}
int school::get_offices() {
return offices;
}
-
7/29/2019 c++ _UNIT_1
33/60
int main()
{ house h;
school s;
h.set_rooms(12);
h.set_floors(3); h.set_area(4500);
h.set_bedrooms(5);
h.set_baths(3);
cout
-
7/29/2019 c++ _UNIT_1
34/60
CONSTRUCTOR AND DESTRUCTORS
ConstructorsAre used to initialize the member variables of the class
when the objects of the class are created.
Must have the same name as that of class name.
Cannot return any value, not even a void type.
Class can have more than one constructors defined in it
(known as overloaded constructors).
Default constructors accept no parameters and are
automatically invoked by the compiler.
-
7/29/2019 c++ _UNIT_1
35/60
Need for Constructors
To initialize a member variable at the time of
declaration
-
7/29/2019 c++ _UNIT_1
36/60
Declaration of Constructors
Example:
class Calculator
{
private:
int number1, number2, tot;
public:
...
Calculator()
{
number1 = number2 = tot = 0;
cout
-
7/29/2019 c++ _UNIT_1
37/60
Destructors
Are used to de-initialize the objects when theyare destroyed.
Are used to clear memory space occupied by a
data member when an object goes out of scope.
Must have the same name as that of the class,
preceded by a ~ (For example: ~Calculator()).
Are automatically invoked.
Can also be explicitly invoked when required.
Cannot be overloaded
-
7/29/2019 c++ _UNIT_1
38/60
Need for Destructors
To de-initialize the objects when they are destroyed.
To clear memory space occupied by a data member
when an object goes out of scope
-
7/29/2019 c++ _UNIT_1
39/60
Declaration of Destructors
Example:/* This Code Shows The Use Of DestructorIn The Calc Class */class Calc
{
private:int number1, number2, tot;
public:
...
~Calc() //Body Of The
//Destructor{
number1 = number2 = tot = 0;
}
};
-
7/29/2019 c++ _UNIT_1
40/60
PARAMETERIZEDCONSTRUCTORS
The constuctors that take arguments are calledparameterized constructors.
Class ABC
{
int i;Public;
char k;
ABC(int a,float b,char c)
{
i=a;j=b;k=c;
}
};
-
7/29/2019 c++ _UNIT_1
41/60
// Using a constructor and destructor.
#include
using namespace std;
#define SIZE 100
// This creates the class stack.
class stack
{ int stck[SIZE];
int tos;
public: stack(); // constructor
~stack(); // destructor void push(int i);
int pop();
};
-
7/29/2019 c++ _UNIT_1
42/60
// stack's constructor function
stack::stack()
{ tos = 0;
cout
-
7/29/2019 c++ _UNIT_1
43/60
void stack::push(int i)
{ if(tos==SIZE)
{
cout
-
7/29/2019 c++ _UNIT_1
44/60
int main()
{ stack a, b; // create two stack objects
a.push(1); b.push(2);
a.push(3);
b.push(4);
cout
-
7/29/2019 c++ _UNIT_1
45/60
THE C++ KEYWORDS
asm auto bool break case catch char class
Const const_cast continue default delete do double
dynamic_cast else enum explicit export extern false
float for friend goto if inline int
long mutable namespace new operator private protected
public register reinterpret_cast return short signed sizeof
Static static_cast struct switch template this throw
true try typedef typeid typename union unsigned using
virtual void volatile wchar_t while
-
7/29/2019 c++ _UNIT_1
46/60
STRUCTURE:
Structures in C++ is a collection of variables.
Structures in C++ can be declared even without the
keyword "struct".
By default all the members of a structure are
"public", even "private" members can also be
declared in a function.
-
7/29/2019 c++ _UNIT_1
47/60
SYNTAX:
struct struct-type-name
{
type name1: length;
type name2: length;
.
.
type nameN : length;
} variable_list;
-
7/29/2019 c++ _UNIT_1
48/60
EXAMPLE:
#include
struct Emp {
int empno; int empsal;
};
void main( )
{ Emp emp1= { 23, 12000};
cout
-
7/29/2019 c++ _UNIT_1
49/60
UNIONS:
Unions in C++ is a user defined data type that uses thesame memory as other objects from a list of objects. Atan instance it contains only a single object.
Syntax:
union union-type-name {
type member-name; type member-name;
}union-variables;
EXAMPLE:
-
7/29/2019 c++ _UNIT_1
50/60
EXAMPLE:
#include
union Emp
{ int num; double sal;
};
int main()
{ Emp value; value.num = 2;
cout
-
7/29/2019 c++ _UNIT_1
51/60
FRIENDFUNCTIONS
It is possible to grant a nonmember function access
to the private members of a class by using a friend.
A friend function has access to all private andprotected members of the class for which it is a
friend.
To declare a friend function, include itsprototype within the class, preceding it with thekeyword friend.
-
7/29/2019 c++ _UNIT_1
52/60
52
INLINEFUNCTIONS (II)
An inline function can never be located in a run-time library since theactual code is inserted by the compiler and must therefore be knownat compile-time.
It is only useful to implement an inline function when the time whichis spent during a function call is long compared to the code in thefunction.
There is an important feature in C++, called an inline function, that iscommonly usedwith classes
In C++, you can create short functions that are not actually calledrather, their code is expanded in line at the point of each invocation.
This process is similar to using a function-like macro.
To cause a function to be expanded in line rather than called,precede its definition with the inline keyword.
#include
-
7/29/2019 c++ _UNIT_1
53/60
#include iostream
using namespace std;
class myclass
{
int a, b; public:
void init(int i, int j);
void show();
};
// Create an inline function.
inline void myclass::init(int i, int j)
{ a = i;
b = j;
}
// Create another inline function. inline void myclass::show()
{ cout
-
7/29/2019 c++ _UNIT_1
54/60
int main()
{
myclass x;
x.init(10, 20);
x.show();
return 0;
}
-
7/29/2019 c++ _UNIT_1
55/60
DEFINING INLINEFUNCTIONS WITHINA CLASS
#include
using namespace std;
class myclass
{ int a, b;
public: // automatic inline
void init(int i, int j)
{ a = i;
b = j;
}
void show() {
cout
-
7/29/2019 c++ _UNIT_1
56/60
PASSINGOBJECTS
Use call-by-value for very small objects
Use call-by-const-reference for large objects
Return a result rather than modify an object through areference argument
Use call-by-reference only when you have to
For exampleclass Image { /* objects are potentially huge*/ };
void f(Image i); f(my_image); // oops: this could be s-l-o-o-o-wvoid f(Image& i); f(my_image); // no copy, butf()can modify
my_imagevoid f(const Image&); f(my_image); // f()wont mess with
my_image
56Stroustrup/Programming
-
7/29/2019 c++ _UNIT_1
57/60
RETURNINGOBJECTS
C++ allows returning of objects.
The objects are returned same as other variables i.e. using
return statement. The function that is returning object must specify the return
type as that of the class of the object.
class AnimalLister{
public:
Animal* getNewAnimal(){Animal* animal1 = new Animal();return animal1; // returning object
}}int main() {AnimalLister al;Animal *a1, *a2;a1 = al.getNewAnimal();a2 = al.getNewAnimal();
}
ASSSIGING OF OBJECTS
-
7/29/2019 c++ _UNIT_1
58/60
ASSSIGINGOFOBJECTS
#include using namespace std;
class MyClass {int a, b;
public:void setAB(int i, intj) { a = i, b = j; }void display() {
cout
-
7/29/2019 c++ _UNIT_1
59/60
ARRAYOFOBJECTS
Array of objects can be created similar to the arrays and datatype as the classname.
#include
using namespace std;
class MyClass {int x;
public:void setX(int i) { x = i; }int getX() { return x; }
};
int main(){MyClass obs[4]; // Array of Objectsint i;
for(i=0; i < 4; i++)obs[i].setX(i);
for(i=0; i < 4; i++)
cout
-
7/29/2019 c++ _UNIT_1
60/60
POINTERSTOOBJECTS
#include using namespace std;class myclass {
int i;public:myclass(intj) {
i = j;}int getInt() {
return i;}
};int main(){
myclass ob(88), *objectPointer;objectPointer = &ob; // get address of ob
cout getInt(); // use -> to call getInt()return 0;}