0% found this document useful (0 votes)
5 views86 pages

C Unit-I

Uploaded by

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

C Unit-I

Uploaded by

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

UNIT-I

1
Prepared By N.KANNAN/AP/CSE/EGSPEC
COURSE OUTCOMES(CO)
1902CS302- Object Oriented Programming(OOP’S)
1. CO1 Define the features of C++ supporting object oriented
programming.

2. CO2 Understand the major object-oriented concepts such that


constructor and operator overloading in C++.

3. CO3 Define the features of Java supporting object oriented


programming.

4. CO4 Understand the concepts for Java Inheritance, Polymorphism


and Java Reflection.

5. CO5 Demonstrate the working of string builder and string buffer


in2 String handling.
MODULE I
INTRODUCTION TO C++

Introduction to C++ Pointers and objects


Classes and objects Constant objects
Access specifiers Nested classes
Function and data memberslocal classes
Default arguments
Function overloading
Friend functions
Const and volatile functions
3
C++ HISTORY
• C++ programming language was development
started in 1979 by Bjarne Stroustrup at bell
laboratories of AT&T (American Telephone &
Telegraph), located in U.S.A.

• C++ was initially known as “C with classes, ” and


was renamed C++ in 1983.

• Bjarne Stroustrup is known as the founder of C++

• It was develop for adding a feature of OOP (Object


Oriented Programming) in C++. 4
INTRO
 C++ is an object-oriented programming language.
It is an extension to C programming.

 C++ is a general purpose, case-sensitive.

 C++ is an multi-paradigm language that supports


procedural, functional, and generic programming
styles.

 C++ is a middle-level language, as it encapsulates


both high and low level language features.
5
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 allows code to be reused.

 C++ is portable and can be used to develop applications that


can be adapted to multiple platforms.

 C++ is easy to learn

 As C++ is close to C,C# and Java, it makes it easy for


programmers to switch to C++ . 6
DIFFERENCE BETWEEN
C &C++

7
ADVANTAGES

 OOP is faster and easier to execute.

 OOP provides a clear structure for the programs..

 OOP helps to makes the code easier to maintain,


modify and debug.

 OOP makes it possible to create full reusable


applications with less code.
8
C++ SYNTAX

Example
#include <iostream.h>// header file library
using namespace std;// we can use names for objects and
variables from the standard library.

int main() //main function


{
cout << "Hello World!";
return 0;
}
9
C++ VARIABLES

• Variables are containers for storing data values.


• In C++, there are different types of variables,
• For example:
 int - stores integers (whole numbers),such as 123 or -123
 double - stores floating point numbers, with decimals, such as 29.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 string - stores text, such as “I am learning C++". String values are
surrounded by double quotes
 bool - stores values with two states: true or false

10
DECLARING (CREATING)
VARIABLES
 To create a variable, specify the type and assign it a value.
Syntax:
Data_type variable_name = value;

Example1:
int age= 15;// Var Declr
cout << age;//print value
Example
2:
int age = 15;
age= 10;
cout << age; 11
C++ DECLARE
MULTIPLE
VARIABLES
 To declare more than one variable of the same type,
use a comma-separated list:

Example
int x = 5, y = 6, z =
50; cout << x + y + z;
12
ONE VALUE TO MULTIPLE
VARIABLES
 You can also assign the same value to multiple
variables in one line.

Example
int x, y, z;
x = y = z = 50;
cout << x + y + z;

13
C++ IDENTIFIERS
 All C++ variables must be identified with unique
names.
 These unique names are called identifiers.
 Identifiers can be short names (like x and y) or more
descriptive names (age, sum, Average).

Example
int minutesPerHour = 60; // Good

int m = 60; // OK, but not easy to understand what m actually


14
IDENTIFIERS RULES

1. Names can contain letters, digits and underscores


2. Names must begin with a letter or an underscore (_)
3. Names are case sensitive
4. Names cannot contain whitespaces or special
characters like !, #, %, etc.
5. Reserved words (like C++ keywords, such as int)
cannot be used as names

15
C++ CONSTANTS

 When you do not want to change existing variable


values,use the const keyword-means unchangeable
and read-only.
Example

const int myNum = 15; // myNum will always be 15

myNum = 10; //error: assignment of read-only variable

16
C++ USER INPUT
 You have already learned that cout is used to output
(print) values. Now we will use cin to get user input.
 cin is a predefined variable that reads data from the
keyboard with the extraction operator (>>).
 In the following example, the user can input a number,
which is stored in the variable x. Then we print the
value of x:
Example
int x;
cout << "Type a number: “;
cin >> x;
cout << "Your number is: " << x;
17
DATA TYPES

18
C++ DATA TYPES SIZE

19
KEYWORDS IN C++

20
PROGRAMMING PARADIGMS
 Programming paradigms are different ways or styles in
which a given program or programming language can be
organized.

21
CHARACTERISTICS OF OOP’S

22
OBJECTS
 Any entity that contains data and its related
functions.
 For example, a chair, pen, table, keyboard, bike, etc.

 An Object can be defined as an instance of a class.


 It can be physical and logical. 23
CLASS
 Collection of objects is called class. It is a logical entity.

 A class can also be defined as a blueprint from which you

can create an individual object.


24
INHERITANCE
 Parent – child relation
 When one object acquires all the
properties and behaviors of a parent
object, it is known as inheritance. It
provides code reusability.

25
TYPES OF INHERITANCE
IN C++

26
POLYMORPHISM

 If one task is performed in different


ways, it is known as polymorphism.

 For example: to draw something, for


example, shape, triangle, rectangle,
etc.

27
ENCAPSULATION
 Meaning of Encapsulation, is to make sure
that "sensitive" data is hidden from other
users.
 Binding code and data together into a
single unit are known as encapsulation.

 Ex: Capsule

28
ABSTRACTION
 Abstraction - Hiding internal details
and showing functionality is known as
abstraction.
 Abstraction means displaying only essential
information and hiding the details.
 For example phone call, we don't know the internal
processing.

Note:
 Data abstraction can be used to provide security for
29

the data from the unauthorized methods.


CLASSES
&
OBJECTS

30
C++ CLASSES
 A Class is a user-defined data type that has data members
and member functions.

 data members and member functions define the properties


and behavior of the objects in a Class.

 In the above example of class Car, the data member will


be speed limit, mileage, etc, and member functions can
be applying brakes, increasing speed, etc.

31
CREATE A CLASS IN C++
 A class is defined in C++ using keyword class followed
by the name of the class.

 The body of the class is defined inside the curly


brackets and terminated by a semicolon at the end.
Syntax: Example:
Class class_name
class Student
{
{
// data member int id;//data member
// member functions string name;//data member
}; void display();//member functions
};
32
C++ OBJECTS
 An Object is an instance of a Class.

 When a class is defined, only the specification for the


object is defined; no memory or storage is allocated.

 To use the data and access functions defined in the


class, we need to create objects.

33
CREATE OBJECT IN C++
Syntax:
Class_name Object_name;

Example:
int main()
{
Student s1; // Create an object of Student
s1.id = 15; // Access attributes &set values
s1.name = ”Ram";
cout << s1.id << "\
n"; cout <<s1.name; // Print attribute values

return 0;
} 34
ACCESS
SPECIFIERS/MODIFIERS

35
C++
ACCESS SPECIFIERS/MODIFIERS
Access specifiers define how the data members and
methods of a class can be accessed.

The data members and methods defined inside a class


are visible to the class itself.

If we want to make these visible to subclasses or


other packages, we need to use access modifiers.

36
TYPES OF ACCESS MODIFIERS
In C++, there are three access modifiers:
1. public - members are accessible from outside the
class
2. private - members cannot be accessed (or viewed)
from outside the class
3. protected - members cannot be accessed from
outside the class, however, they can be accessed in
inherited classes.

37
PUBLIC ACCESS MODIFIER
 The public keyword is used to create public members
(data and functions).
 The public members are accessible from any part of
the program.

SYNTAX:

public data_type variable_name


(Or)
public return_type method_name()

{
// data member
// member functions
}; 38
Example 1: int main()
C++ public Access Modifier {
class Sample // declare a class object
{ Sample obj1;
public: // public elements cout << "Enter your age: ";
int age; cin >> obj1.age;
void displayAge() obj1.displayAge();
{ return 0;
cout << "Age = " << age << endl; }
}
};

39
PRIVATE ACCESS MODIFIER
 The private keyword is used to create private
members (data and functions).
 The private members can only be accessed from
within the class.
 However, friend classes and friend functions can
access private members.

SYNTAX:
private data_type variable_name
(Or)
private return_type method_name()

{
// data member
// member functions
40
};
Example 2: int main()
C++ private Access Specifier {
class Sample int ageInput;
{ Sample obj1; //Object Declr
private: //private elements
cout << "Enter your age: ";
int age;
cin >> ageInput;
private: // public method
obj1.displayAge(ageInput);
void displayAge(int a)
return 0;
{
}
age = a;
.
cout << "Age = " << age << endl;
} cin >> obj1.age; // error
In main(), the object obj1 cannot
};
directly access the
41
class variable age
PROTECTED ACCESS MODIFIER
 Before we learn about the protected access specifier,
make sure you know about inheritance in C++.
 The protected keyword is used to create protected
members (data and function).
 The protected members can be accessed within the
class and from the derived class.

SYNTAX:
protected data_type variable_name
(Or)
protected return_type method_name()

{
// data member
// member functions
42
};
STATIC MEMBER DATA
&
STATIC MEMEBR FUNCTION
CLASS SPECIFICATION
SYNTAX:
Class Class_name
{
Data member

Member function
}

44
INTRODUCTION
Data Members:
 The variables declared inside the class are known as data
members.
 Data members may be private or public.

Member functions:
 The functions declared inside the class are known as
member functions.
 Member functions are methods or functions that are
defined inside of objects.
 Generally used to manipulate data members and other
object data. 45
STATIC DATA MEMBERS
 Define the data member of a class using the static
keyword, the data members are called the static data
member.
 A static data member is similar to the static member
function because the static data can only be accessed
using the static data member or static member function.
 All the objects of the class share the same copy of the
static member to access the static data.

46
DECLARE STATIC DATA
MEMBER
Syntax:
static data_type data_member_name;
Ex:
Class Demo
{
Static int count;
}

47
class rectangle
void output()
{ {
private: count++;
area=length*width;
int length; cout<<"area of rectangle"<<count<<"is=“
<<area<<endl;
int width;
}
int area; };
int rectangle::count;
static int count;
int main()
public: {
rectangle r1, r2,
void input()
r3; r1.input();
{ r1.output();
r2.input();
cout<<"enter the len"<<endl; r2.output();
cin>>length; r3.input();
r3.output();
cout<<"enter the width"<<endl; return 0;
cin>>width; }

}
48
STATIC MEMBER FUNCTIONS
 Its special functions used to access the static data
members or other static member functions.
 A member function is defined using the static
keyword.
 A static member function shares the single copy of
the member function to any number of the class'
objects.
 We can access the static member function using the
class name or class' objects.

49
class Member int Member :: A = 20;
{ int Member :: B = 30;
private:static int A,B,C; int Member :: C = 40;

public:static int count; int main ()

Member() {

{ Member mb;
cout << " Print the static member
count++;
through object name: " << endl;
}
mb. disp();
static void disp() cout << " Print the static member
{ through the class name: " << endl;

cout << " The value of A is: " <<A ; Member::disp();

cout << " The value of B is: " <<B; return 0;

cout << " The value of C is: " <<C; }

} 50

};
DEFAULT ARGUMENTS
(PARAMETERS)
 In C++ programming, we can provide default values
for function parameters.

 If a function with default arguments is called without


passing arguments, then the default parameters are
used.

 However, if arguments are passed while calling the


function, the default arguments are ignored.

 In case any value is passed, the default value is


overridden.
Example:
#include <iostream>
using namespace std;
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
52

}
C++ FUNCTIONS
 A function is a group of statements that together
perform a specific task.

 Every C++ program has at least one function, which is


main().

 Functions are used to perform certain actions, and


they are important for reusing code.

53
ADVANTAGE OF FUNCTION

 Code Re-usability

 Develop an application in module format.

 Easily to debug the program.

 Code optimization: No need to write lot of code.

54
FUNCTION ASPECTS
There are three aspects of a C function.
 Function declaration
- A function must be declared globally.
 Function call
-Function can be called from anywhere in the program.
-The parameter list must be same in function calling and
declaration.
 Function definition
-The actual body of the function can be defined separately.

55
FUNCTION ASPECTS

56
TYPE OF FUNCTION

57
PRE-DEFINED FUNCTIONS
 The pre-defined functions or library functions are
built-in functions.

 The user can use the functions, but cannot modify


the function.

 Example: sqrt(),clrscr(),getch(),etc…,

58
USER-DEFINED FUNCTIONS
 The functions defined by the user for their
requirement are called user-defined functions.

 Whenever it is needed, The user can modify the


function.

 Example: sum(a,b)

59
ADVANTAGE OF USER-DEFINED
FUNCTIONS
 Avoid rewriting same logic/code again and again.

 Call C functions any place in a program.

 large C ++ program easily when it is divided into

multiple functions.

 Code Reusability.

60
C++ OVERLOADING
 If we create two or more members having the same
name but different in number or type of parameter, it
is known as C++ overloading.

 Types of overloading in C++

61
C++ FUNCTION OVERLOADING
 Function Overloading is defined as the process of
having two or more function with the same name, but
different in parameters is known as function
overloading.
 n function overloading, the function is redefined by
using either different types of arguments or a
different number of arguments.

62
FUNCTION OVERLOADING - NUMBER OF ARGUMENTS VARY.
#include <iostream> return a + b + c;
using namespace std;
class Cal
{
public:
static int add(int a,int b)
{
return a + b;
}
static int add(int a, int b, int
c)
{
} 63

};
int main(void)
{
Cal C;
cout<<C.add(10,
20)<<endl;
cout<<C.add(12, 20,
23);
return 0;
}
FUNCTION OVERLOADING -DIFFERENT TYPES OF ARGUMENTS

#include<iostream> int main()


using namespace std; {
int mul(int,int); int r1 = mul(6,7);
float mul(float,int); float r2 = mul(0.2,3);
int mul(int a,int b) cout << "r1 is : " <<r1<< endl;
{ cout <<"r2 is : " <<r2<< endl;
return a*b; return 0;
} }
float mul(double x, int y)
{
return x*y;
} 64
FRIEND FUNCTION
 Friend function can be granted special access to
private and protected members of a class in C++.

 They are the non-member functions that can access


and manipulate the private and protected members of
the class for they are declared as friends.

65
Friend function used to print the length of
the box
#include <iostream> int printLength (Box b)
Using namespace {
b. length =10;
std; class Box return b.
{ length;
}
private: int main ()
{
int length;
Box b;
public: cout <<"Length of box:"<<printLength(b);
return 0;
}
friend int printLength (Box);
};
66
CONST
&
VOLATILE FUNCTIONS

67
CONSTANT FUNCTIONS
 Member function does not alter any data in the class.

 The keyword const is placed between the argument


list and the body of the function.

SYNTAX:
<return type> <function name> (argument1,argument 2)const
{
<the function body>
}

68
#include <iostream> int main()
using namespace {
std; class sample sample s;
{ s.disp();
public: int a=10; return 0
void disp()const }
{
cout<<a++;
ERROR DISPLAYED
} CAN NOT MODIFY A CONST OBJECT

};
69
MUTABLE DATA MEMBERS
 Data members cannot be modified by the const
function.
 If a data member is declared as mutable the it can be
even modified by const function.

SYNTAX:
mutable data_type variable_name;
EX:
mutable int a;
70
#include <iostream> };
using namespace int main()
std; class sample {
{ sample s;
public: s.a=10;
mutable int a=10; s.disp();
void disp()const return 0
{ }
cout<<a++; 10

}
71
VOLATILE FUNCTIONS
 A member function can be declared as volatile if it is
invoked by volatile object.

 Volatile objects value can be changed by external


parameters which are not under the control of the
program.

 Example: An object taking input from NIC does not take


input from our program. As and when hardware
interrupts the value related to change without our
programs knowledge.

72
class B cout<<z;
{ }
volatile int };
x=10; const int int main()
y=5; public: {
volatile void f() B b;
{ b.f();
cout<<x<<endl; return 0;
cout<<y<<endl; }
x++;
cout<<x<<endl;
z++; 73
CONSTANT OBJECTS

 .Create an object using the const keyword, the value of


data members can never change till the life of the
object in a program. The const objects are also known
as the read-only objects.

 SYNTAX:
const class_name obj_name;

74
#include <iostream>
using namespace std;
class obj
{
public:
int a=10;
};
int main ()
{
const obj b;
cout << " The value of A: " <<b.a << endl;
// b.a = 20; // It returns a compile time error
return 0; 75

}
POINTER TO OBJECT IN C++

 A pointer is a variable that stores the memory address


of another variable (or object) as its value.

 Pointers to objects aim to make a pointer that can


access the object, not the variables. Pointer to object
in C++ refers to accessing an object.

 SYNTAX:
classname *pointertoobject;

76
#include <iostream> int getArea()
using namespace std; {
class Rectangle return 2*length*breadth;
{ }
private: };
int length; int main()
int breadth; {
public: Rectangle var1(10,30);
Rectangle(int l, int b) Rectangle* ptr = &var1;
{ int area = ptr->getArea();
length=l; cout<<"Area of Rect is:”
breadth=b; <<area;
return 0;
} 77

}
LOCAL CLASSES IN C++

 A class declared inside a function becomes local to


that function and is called Local Class in C++.

 A local class name can only be used locally i.e., inside


the function and not outside it.

 The methods of a local class must be defined inside it


only.

 The local class can’t access the non-static variable of


the function
78
class A public:
{ int y=60,z=70;
public: void show()
int x=50; {
void show() cout << " y=" << y;
{ cout << " z=" << z;
cout << " x=" << x; cout << " w=" << w;
} }
}; };
int w = 80; // global A a;
variable int main() a.show();
{ B b;
static int z=100; // static b.show();
variable class B // local class }
79
{
NESTED CLASSES IN C++
 we can declare the class within another class and
a class declared as a member of another class is called
a nested class.
 Syntax of the nested class declaration:

class outer_class_name // outer class


{
class inner_class_name //inner class
{
private:
public:
}; end of inner class
};end of outer class
80
class student int main()
{ {
public: student x;
char name[20]="Raj"; student::date y;
int rollno=100; cout<<“Name :"<<x.name;
class date cout<<"Regno:"<<x.rollno;
{ cout<<“Year:"<<y.year;
public: }
char Year[20]="Final";
};
};

81
82

You might also like