[go: up one dir, main page]

0% found this document useful (0 votes)
25 views26 pages

Module 1 C

This document provides an introduction to C++, covering its history, similarities and differences with C, characteristics, and the principles of object-oriented programming (OOP). It explains key concepts such as classes, objects, encapsulation, inheritance, and polymorphism, highlighting the advantages of C++ in software development. The document also discusses the applications of OOP and the importance of understanding its concepts for effective programming.

Uploaded by

mobilemagic9773
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views26 pages

Module 1 C

This document provides an introduction to C++, covering its history, similarities and differences with C, characteristics, and the principles of object-oriented programming (OOP). It explains key concepts such as classes, objects, encapsulation, inheritance, and polymorphism, highlighting the advantages of C++ in software development. The document also discusses the applications of OOP and the importance of understanding its concepts for effective programming.

Uploaded by

mobilemagic9773
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Introduction to C++ Module-1

Module-1
Introduction to Object Oriented Programming

History of C++:
 The C++ programming language was created by Bjarne Stroustrup (1980) and his
team at Bell Laboratories (AT&T, USA) to help implement simulation projects in an
object oriented and efficient way.
 C++ can make use of existing C software libraries with major addition of “Class
Construct”.
 This language was called “C with classes” and later in 1983, it was named “C++” by
Rick Mascitii. As the name C++ implies, C++ was derived from the C programming
language: ++ is the increment operator in C.

Why Use C++

 C++ is one of the world's most popular programming languages.


 C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.
 C++ is an object-oriented programming language which gives a clear structure to
programs and allows code to be reused, lowering development costs.
 C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.
 C++ is fun and easy to learn!

Similarities between C and C++

 Both languages have the same code structure.

 They both have a similar syntax.

 They both have a similar compilation.

 Their basic memory model is very close to the hardware.

Dept. of CSE,RYMEC,Ballari Page 1


Introduction to C++ Module-1

 Both the languages share the same basic syntax. Also, almost all the operators and
keywords of C are present in C++ as well, and they do the same thing.

 Similar notions of heap, stack, static, and file-scope variables are present in both of
these languages.

 As compared to C, C++ has more extended grammar. But the basic grammar here is
the same.

Difference between C and C++

No. C C++
C follows the procedural style C++ is multi-paradigm. It supports
1.
programming. both procedural and object oriented.
In C++, you can use modifiers for class
2. Data is less secured in C. members to make it inaccessible for outside
users.

3. C follows the top-down approach. C++ follows the bottom-up approach.

C does not support function


4. C++ supports function overloading.
overloading.
In C, you can't use functions in
5. In C++, you can use functions in structure.
structure.
C does not support reference
6. C++ supports reference variables.
variables.
In C, scanf() and printf() are C++ mainly uses stream cin and cout to
7.
mainly used for input/output. perform input and output operations.
Operator overloading is not
8. Operator overloading is possible in C++.
possible in C.
C programs are divided C++ programs are divided into functions and
9.
into procedures and modules classes.
C does not provide the feature of
10. C++ supports the feature of namespace.
namespace.
Exception handling is not easy in C.
C++ provides exception handling using Try and
11. It has to perform using other
Catch block.
functions.

12. C does not support the inheritance. C++ supports inheritance.

Dept. of CSE,RYMEC,Ballari Page 2


Introduction to C++ Module-1

Characteristics of C++:

 Object-Oriented Programming: It allows the programmer to design applications


like a communication between object rather than on a structured sequence of code.
It allows a greater reusability of code in a more logical and productive way.
 Portability: We can compile the same C++ code in almost any type of computer &
operating system without making any changes.
 Modular Programming: An application’s body in C++ can be made up of several
source code files that are compiled separately and then linked together saving time.
 C Compatibility: Any code written in C can easily be included in a C++ program
without making any changes.
 Speed: The resulting code from a C++ compilation is very efficient due to its duality
as high level and low-level language.
 Machine independent: It is a Machine Independent Language.
 Flexibility: It is highly flexible language and versatility.
 Wide range of library functions: It has huge library functions; it reduces the code
development time and also reduces cost of software development.
 System Software Development: It can be used for developing System Software
Viz., Operating system, Compilers, Editors and Database.

Object-Oriented Programming
Is a Procedural programming is about writing procedures or functions that perform
operations on the data, while object-oriented programming is about creating objects that
contain both data and functions.

Dept. of CSE,RYMEC,Ballari Page 3


Introduction to C++ Module-1

OOPs characteristics:
 Modularity: Module is a logically self-contained unit that can be tested and
executed independently.
 Abstraction: Abstraction is the process of only showing the necessary details to the
user and hiding the other details in the background.
 Data Encapsulation: Wrapping of data and functions into a single unit is called data
encapsulation.
 Inheritance: The process by which objects of one class acquires the properties of
the objects of another class.
 Polymorphism: The ability for a message to be processed in more than one form.
 Dynamic Binding: Linking of a procedure call to the code to be executed when it is
called.
 Message Passing: Message passing in C++ is the method of communication
between two or more objects. A message is used to communicate with other objects
by invoking the function of other objects.

Differences between Object-based and Object-oriented Programming

 Object-based programming: Object-based programming uses objects and classes


but without inheritance. It provides flexibility to the program and is easier to work
with. Operator overloading, function overloading, and the use of constructors and
destructors are included in object-based programming.

 Object-oriented programming: Object-oriented programming uses classes and


objects with inheritance. It can have classes inherited from other classes and have
complex means for calling and using functions of both the classes. Base (or parent)
classes (from which we derive or inherit another class) and inherited or derived
(from base classes) classes are the two categories of classes. It is possible to inherit
a class from multiple classes and it is also possible to inherit multiple classes from a
single class. An already inherited class can also be inherited further.

Dept. of CSE,RYMEC,Ballari Page 4


Introduction to C++ Module-1

C++: Not Completely Object-oriented


 Pure object-oriented models are never found efficient, but the C++ model is a
balanced one chosen to cater to efficiency as the prime requirement.
 There are other languages such as Java, which offer better object orientation but are
less efficient than C++. Hence, C++ does not represent the pure object-oriented
model.
 The C++ model is very close to the object-oriented philosophy but not completely so.
It is also possible to write a C++ program without using the object-oriented
methodology.
 A valid C program without any object orientation feature is usually a valid C++
program as well. The basic requirements of object orientation and object-based
programming include providing classes.
 Besides, other issues such as encapsulation, inheritance, polymorphism, and
reusability of code and objects are required to be implemented.
 Let us now look at some of the object-oriented concepts that would help us
understand the design of the C++ language and the psychology behind its creation.

Dept. of CSE,RYMEC,Ballari Page 5


Introduction to C++ Module-1

Object-Oriented Programming Paradigm

 The major motivating factor in the invention of object-oriented approach is to


remove some of the flaws encountered in the procedural approach.
 OOP treats data as a critical element in the program development and does not
allow it to flow freely around the system.
 It ties data more closely to the functions that operate on it, and protects it from
accidental modification from outside functions.
 OOP allows decomposition of a problem into a number of entities called objects and
then builds data and functions around these objects.
 The organization of data and functions in object-oriented programs is shown in Fig.
 The data of an object can be accessed only by the functions associated with that
object. However, functions of one object can access the functions of other objects.

Dept. of CSE,RYMEC,Ballari Page 6


Introduction to C++ Module-1

Applications of OOP

Importance in many areas. The most popular application of object-oriented


programming, up to now, has been in the area of user interface design such as
windows. Hundreds of windowing systems have been developed, using the OOP
techniques.
Real-business systems are often much more complex and contain many more
objects with complicated attributes and methods. OOP is useful in these types of
applications because it can simplify a complex problem. The promising areas for
application of OOP include:

 Real-time systems
 Simulation and modeling
 Object-oriented databases
 Hypertext, hypermedia and expertext
 AI and expert systems
 Neural networks and parallel programming.
 Decision support and office automation systems
 CIM/CAM/CAD systems

Object Oriented Programming


It is necessary to understand some of the concepts used extensively in object-oriented
programming.
These include
 Classes
 Objects
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Message passing

Dept. of CSE,RYMEC,Ballari Page 7


Introduction to C++ Module-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 use.
 When defining a class, we are creating a new abstract data type that can be
treated like any other built-in data type. Generally, a class specification has two
parts:
1. Class declaration

2. Class function definitions


The class declaration describes the type and scope of its members. The class
function definitions describe how the class functions are implemented.
The general form of a class declaration is

class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declaration;
};

The class declaration is similar to a struct declaration. The keyword class specifies,
that what follows is an abstract data of type class_name. The body of a class is enclosed
within braces and terminated by a semicolon. The class body contains the declaration of
variables and functions. These functions and variables are collectively called class
members. They are usually grouped under two sections, namely, private and public to
denote which of the members are private and which of them are public. The keywords
private and public are known as visibility labels. Note that these keywords are followed
by a colon.
The class 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

Dept. of CSE,RYMEC,Ballari Page 8


Introduction to C++ Module-1

class also. The data hiding (using private declaration) is the key feature of object-oriented
programming. The use of the keyword private is optional. By default, the members of a
class are private. If both the labels are missing, then, by default, all the members are
private. Such a class is completely hidden from the outside world and does not serve any
purpose.
The variables declared inside the class are known as data members and the
functions are known as member functions. Only the member functions can have access to
the private data members and private functions. However, the public members (both
functions and data) can be accessed from outside the class. This is illustrated in Fig. 1.1.
The binding of data and functions together into a single class-type variable is referred to
as encapsulation.

Fig. 1.1 Data hiding in classes


A Simple Class Example
A typical class declaration would look like
class item
{
int number; // variables declaration
float cost; // private by default
public:
void getdata(int a, float b); // functions declaration void
putdata(void); // using prototype
}; // ends with semicolon

Dept. of CSE,RYMEC,Ballari Page 9


Introduction to C++ Module-1

We usually give a class some meaningful name, such as item. This name now becomes
a new type identifier that can be used to declare instances of that class type. The class
item contains two data members and two function members. The data members are
private by default while both the functions are public by declaration. The function
getdata() can be used to assign values to the member variables number and cost, and
putdata() for displaying their values. These functions pro- vide the only access to the data
members from outside the class. This means that the data cannot be accessed by any
function that is not a member of the class item. Note that the functions are declared, not
defined. Actual function definitions will appear later in the program. The data members
are usually declared as private and the member functions as public. Figure 1.2 shows
two different notations used by the OOP analysts to represent a class.

 private, protected, and public is called visibility labels.


 The members that are declared private can be accessed only from within the class.
 Public members can be accessed from outside the class also.
 protected members cannot be accessed from outside the class, however, they can be
accessed in inherited classes.
 In C++, data can be hidden by making it private.

Objects

 Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program must handle.

 The fundamental idea behind object oriented approach is to combine both data and
function into a single unit and these units are called objects.

Dept. of CSE,RYMEC,Ballari Page 10


Introduction to C++ Module-1

Creating Objects:

Remember that the declaration of item as shown above does not define any objects
of item but only specifies what they will contain. Once a class has been declared, we can
create variables of that type by using the class name (like any other built-in type variable).

Fig. 1.3 Representation of a class

For example,

item x; // memory for x is created

creates a variable x of type item. In C++, the class variables are known as objects.
Therefore, x is called an object of type item. We may also declare more than one object in
one statement. Example: item x, y, z;

The declaration of an object is similar to that of a variable of any basic type. The
necessary memory space is allocated to an object at this stage. Note that class
specification, like a structure, provides only a template and does not create any memory
space for the objects.

Dept. of CSE,RYMEC,Ballari Page 11


Introduction to C++ Module-1

Objects can also be created when a class is defined by placing their names
immediately after the closing brace, as we do in the case of structures.
That is to say, the definition
class item
{
.....
.....
.....
} x,y,z;

would create the objects x, y and z of type item. This practice is seldom followed
because we would like to declare the objects close to the place where they are used and
not at the time of class definition.

Accessing Class Members

As pointed out earlier, the private data of a class can be accessed only through the
member functions of that class. The main() cannot contain statements that access
number and cost directly. The following is the format for calling a member function :

object-name.function-name (actual-arguments);

For example, the function call statement

x.getdata(100,75.5);
is valid and assigns the value 100 to number and 75.5 to cost of the object x by
implementing the getdata() function. The assignments occur in the actual function. Please
refer Sec. 5.4 for further details.
Similarly, the statement

x.putdata();
would display the values of data members. Remember, a member function can be
invoked only by using an object (of the same class).

Dept. of CSE,RYMEC,Ballari Page 12


Introduction to C++ Module-1

The statement like

getdata(100,75.5);
has no meaning. Similarly, the statement

x.number = 100;
is also illegal. Although x is an object of the type item to which number belongs, the
number (declared private) can be accessed only through a member function and not by
the object directly.
It may be recalled that objects communicate by sending and receiving messages. This is
achieved through the member functions.
For example,

x.putdata();
sends a message to the object x requesting it to display its contents.
A variable declared as public can be accessed by the objects directly.
Example:

class xyz
{
int x;
int y;
public:
int z;
};
.....
.....
xyz p;
p.x = 0; // error, x is private
p.z = 10 // OK, z is public
.....
.....

Dept. of CSE,RYMEC,Ballari Page 13


Introduction to C++ Module-1

Defining Member Functions


Member functions can be defined in two places:
• Outside the class definition
• Inside the class definition
It is obvious that, irrespective of the place of definition, the function should perform the
same task. Therefore, the code for the function body would be identical in both the
cases. However, there is a subtle difference in the way the function header is defined.
Both these approaches are discussed in detail in this section.

Outside the Class Definition:


Member functions that are declared inside a class have to be defined separately
outside the class. Their definitions are very much like the normal functions. They should
have a function header and a function body. Since C++ does not support the old version
of function definition, the ANSI prototype form must be used for defining the function
header.
An important difference between a member function and a normal function is that a
member function incorporates a membership ‘identity label’ in the header. This ‘label’
tells the compiler which class the function belongs to. The general form of a member
function definition is

return-type class-name::function-name(argument declaration)


{
Function body
}

The membership label class-name :: tells the compiler that the function function-
name belongs to the class class-name. That is, the scope of the function is restricted to the
class-name specified in the header line. The symbol :: is called the scope resolution
operator.

For instance, consider the member functions getdata() and putdata() as discussed
above.

Dept. of CSE,RYMEC,Ballari Page 14


Introduction to C++ Module-1

They may be coded as follows:

void item :: getdata(int a, float b)


{
number = a;
cost = b;
}
void item :: putdata(void)
{
cout << “Number :” << number << “\n”;
cout << “Cost :” << cost << “\n”;
}

Since these functions do not return any value, their return-type is void. Function
arguments are declared using the ANSI prototype.
The member functions have some special characteristics that are often used in the
program development.
These characteristics are:
 Several different classes can use the same function name. The ‘membership label’
will resolve their scope.
 Member functions can access the private data of the class. A nonmember
function cannot do so. (However, an exception to this rule is a friend function
discussed later.)
 A member function can call another member function directly, without using the dot
operator.

Inside the Class Definition:


Another method of defining a member function is to replace the function declaration by
the actual function definition inside the class. For example, we could define the item
class as follows:

Dept. of CSE,RYMEC,Ballari Page 15


Introduction to C++ Module-1

class item
{
int number;
float cost;
public:
void getdata(int a, float b); // declaration
// inline function
void putdata(void) // definition inside the class
{
cout << number << “\n”;
cout << cost << “\n”;
}
};

When a function is defined inside a class, it is treated as an inline function. Therefore,


all the restrictions and limitations that apply to an inline function are also applicable
here. Normally, only small functions are defined inside the class definition.

Data Abstraction
 Data Abstraction is a process of providing only the essential details to the outside
world and hiding the internal details, i.e., representing only the essential details in
the program.
 Data Abstraction is a programming technique that depends on the separation of the
interface and implementation details of the program.
 Let's take a real life example of AC, which can be turned ON or OFF, change the
temperature, change the mode, and other external components such as fan, swing.
But, we don't know the internal details of the AC, i.e., how it works internally. Thus,
we can say that AC seperates the implementation details from the external interface.
 C++ provides a great level of abstraction. For example, pow() function is used to
calculate the power of a number without knowing the algorithm the function
follows.
 Since the classes use the concept of data abstraction, they are known as Abstract
Data Types(ADT).

Dept. of CSE,RYMEC,Ballari Page 16


Introduction to C++ Module-1

Encapsulation
 The wrapping up of data and functions into a single unit (called class) is known
as encapsulation.
 Data encapsulation is the most striking feature of a class. The data is not accessible
to the outside world, and only those functions which are wrapped in the class can
access it.
 These functions pro- vide the interface between the object’s data and the program.
This insulation of the data from direct access by the program is called data hiding
or information hiding.

Inheritance
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification. For example,
the bird ‘robin’ is a part of the class ‘flying bird’ which is again a part of the class ‘bird’. The
principle behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated in Fig. 1.3.

Fig. 1.3 Property inheritance

Dept. of CSE,RYMEC,Ballari Page 17


Introduction to C++ Module-1

 In OOP, the concept of inheritance provides the idea of reusability. This means
that we can add additional features to an existing class without modifying it.
 This is possible by deriving a new class from the existing one. The new class will
have the combined features of both the classes.
 The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to
tailor the class in such a way that it does not intro- duce any undesirable side-
effects into the rest of the classes.
 Note that each sub-class defines only those features that are unique to it.
Without the use of classification, each class would have to explicitly include all of
its features.

Polymorphism

 Polymorphism is another important OOP concept. Polymorphism, a Greek term,


means the ability to take more than one form.
 An operation may exhibit different behaviors in different instances. The behavior
depends upon the types of data used in the operation.
 For example, consider the operation of addition. For two numbers, the operation
will generate a sum. If the operands are strings, then the operation would produce
a third string by concatenation.
 The process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
Figure 1.4 illustrates that a single function name can be used to handle
different number and different types of arguments. This is something similar to a
particular word having several different meanings depending on the context. Using a
single function name to perform different types of tasks is known as function overloading.

Dept. of CSE,RYMEC,Ballari Page 18


Introduction to C++ Module-1

Fig. 1.4 Polymorphism

 Polymorphism plays an important role in allowing objects having different


internal structures to share the same external interface.
 This means that a general class of operations may be accessed in the same manner
even though specific actions associated with each operation may differ.
Polymorphism is extensively used in implementing inheritance.

Abstract Data Type


 A class with a defined set of operations and values is known as an abstract data type
(or ADT).
 An abstract data type is a data type whose behavior is defined by the qualities and
functions within a class.
 Or we use structure to use an object of the clas
classs to have the specific abstract data
types.

Complex C1(2,3), C2;


Point P(2,3), Q(4,S), R(10,10),S;
Circle C(P,20), Ring;
Rectangle Rect(P,R), PlayGround;

Dept. of CSE,RYMEC,Ballari Page 19


Introduction to C++ Module-1

Message Passing
 In OOP, message passing refers to communication between objects or processes
where data or signals are exchanged, often through method calls or events,
promoting a modular and flexible design.
 It is a process by which objects communicate by exchanging messages, typically in
the form of method or function calls.

Example:

Objects have a life cycle. They can be created and destroyed. Communication with an object
is feasible as long as it is alive.

Dept. of CSE,RYMEC,Ballari Page 20


Introduction to C++ Module-1

General Structure of C++ Program.


Different programming languages have their own format of coding.

The basic components of a C++program are:


 Comments or Documentation Section
 Pre-processor Directives (Linker Section):
 Definition
 Global Declaration
 main ( ) function
 Declarations
 Statements

Example:

#include <iostream.h> // include header file


#include <conio.h>
void main()
{
cout << “C++ is better than C.\n”; // C++ statement
getch();
} // End of example

Dept. of CSE,RYMEC,Ballari Page 21


Introduction to C++ Module-1

Translating a C++ program


 Computers execute binary instructions.
 These binary instructions are known as machine instructions or machine code.
 The program creation process consists of the following steps:
Step 1 – Write the program in a computer language humans can read and understand
(like C++),
Step 2 – Save the programs in text files as (.cpp) extension. Programs can be a few lines
long and reside in one file or can consist of many millions of lines of code and span
thousands of files,
Step 3 – Run the source code files through a program called a compiler to generate
object code for the target computer,
Step 4 – Run the object files through a program called a linker to produce an executable
image.

Dept. of CSE,RYMEC,Ballari Page 22


Introduction to C++ Module-1

Programming Examples:

1. Average of Two Numbers

#include <iostream.h>
#include <conio.h>
void main()

float number1, number2, sum, average;

cout << “Enter two numbers: ”; // prompt

cin >> number1; // Reads numbers

cin >> number2; // from keyboard

sum = number1 + number2;

average = sum/2;

cout << “Sum = ” << sum << “\n”;

cout << “Average = ” << average << “\n”;

getch();

Dept. of CSE,RYMEC,Ballari Page 23


Introduction to C++ Module-1

2. Swapping of TWO Numbers

#include<iostream.h>
#include<conio.h>
void main()
{
int a = 5, b = 10, temp;
clrscr();
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "\n After swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
getch();
}

Dept. of CSE,RYMEC,Ballari Page 24


Introduction to C++ Module-1

3. Find Size of a Variable

#include<iostream.h>

#include<conio.h>

void main()

char c;

int a;

float b;

double d;

clrscr();

cout << "Size of char: " << sizeof(c) << " byte" << endl;

cout << "Size of int: " << sizeof(a) << " bytes" << endl;

cout << "Size of float: " << sizeof(b) << " bytes" << endl;

cout << "Size of double: " << sizeof(d) << " bytes" << endl;

getch();

Dept. of CSE,RYMEC,Ballari Page 25


Introduction to C++ Module-1

4. Use of Class

#include <iostream.h>
#include <conio.h>

class person
{
char name[30];
int age;
public:
void getdata(void);
void display(void);
};
void person :: getdata(void)
{
cout << “Enter name: ”;
cin >> name;
cout << “Enter age: ”;
cin >> age;
}
void person :: display(void)
{
cout << “\nName: ” << name;
cout << “\nAge: ” << age;
}
void main()
{
person p;
p.getdata();
p.display();
getch();
}

Dept. of CSE,RYMEC,Ballari Page 26

You might also like