Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Unit-1: Principles of Object-Oriented Programming
1. Introduction of OOP, Compare OOP with POP
2. Concept of OOP – Object, Class, Inheritance, Encapsulation, Polymorphism,
Abstraction, Message Passing
3. Structure of C++ Program
4. Data type, Constant, Variable, Statement & Operators
5. Input/output statements
6. Declaration & Creation of Class and Object
7. Data Members and Member functions
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 1 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.1 Introduction of OOP
C++ (C plus plus) is an object-oriented programming language. C++ is an advance or next
version of C programming language. OOP (Object-oriented programming) language is a
methodology or model to develop program using classes and objects.
It was developed by Bjarne Stroustrup at AT & T Bell Laboratory in Murray Hill, New
Jersey, USA in 1979. C++ is a case sensitive programming language. Most of the C concept
applies to C++ also. The most important facilities that C++ adds is the concept of OOP's
(Object Oriented Programming).
Q.2 Compare OOP with POP
Sr.No POP OOP
1 Basic Procedure/Structure Object oriented Programming
oriented Programming
2 Approach Top-down. Bottom-up.
3 Division Large program is Entire program is divided into objects.
divided into units
called functions.
4 Support It Emphasizes It supports code reusability, modularity and
simplicity, clarity, and flexibility.
speed.
5 Entity accessing No access specifiers Access specifiers are "public", "private",
mode available "protected".
6 Data hiding & There is no proper Data is hidden in three modes public,
security way of hiding the data, private, and protected. hence data security
so data is insecure increases.
7 Data sharing Global data is shared Data is shared among the objects through
among the functions in the member functions.
the program.
8 Encapsulation, There is no provision There is provision of encapsulation,
inheritance and of encapsulation, inheritance and polymorphism
polymorphism. inheritance and
polymorphism
9 Overloading There is not support of There is support of operator and function
concept operator and function overloading
overloading
10 Friend No concept of friend
There is a concept of friend function and
functions or function. friend classes.
friend classes Note: "friend" keyword is used only in
C++
11 Virtual classes No concept of virtual Concept of virtual function appear during
or virtual classes. inheritance
function
12 Examples C, VB,Fortran,Pascal C++, JAVA, VB.NET, C#, Python
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 2 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.3 Explain basic Concept of OOP.
It is necessary to understand some of the concepts used extensively in object-oriented
programming. These include:
1. Objects
2. Classes
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing
1. Objects:
Objects are the basic run-time entities in an object-oriented system. It may represent a
person, a place, a bank account, a table of data or any item that the program has to
handle. They may also represent user-defined data such as vectors, time and lists. So, class
variable is known as object. Programming problem is analyzed in terms of objects and nature
of communication between them. Objects take up space in memory and have an associated
address like a record in Pascal or a structure of C.
When a program is executed, the objects interact by sending messages to one another. For
example, if “customer” and “account” are two objects in a program, then the customer object
may send a message to the account object requesting for the bank balance.
Each object contains data and code to manipulate the data. It is sufficient to know the type of
message accepted, and the type of response returned by the objects. Figure shows two
notations that are popularly used in object-oriented analysis and design.
class: STUDENT STUDENT
Total
DATA
Name
Date-of-birth
Marks Average
…………………
FUNCTIONS
Total
Average Display
Display
…………. Two way of representing an object
………….
Object: classname variablename;
For example;
student s1; //Here s1 is an object of class student.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 3 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
❖ Classes:
A class is a collection of objects of similar type. For example, mango, apple and orange are
members of the class fruit. Classes are user-defined data types and behave like the built-in
types of a programming language. The syntax used to create an object is no different than the
syntax used to create an integer in C.
For example,
fruit mango;
will create an object mango belonging to the class fruit.
❖ Data Encapsulation and Data Abstraction
The wrapping up of data and functions into a single unit (called class) is known as data
encapsulation. Data encapsulation is the most striking features 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 provide 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.
Data Abstraction refers to the act of representing essential features without including the
background details or explanations. For example, floating-point numbers are abstracted in
programming language. You are not required to know how a floating-point number is
represented in binary while assigning a value to it.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight and cost and functions to operate on these attributes.
They encapsulate all the essential properties of the objects that are to be created. The
attributes are sometimes called data members because they hold information. The functions
that operate on these data are sometimes called methods or member functions.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 4 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
❖ Inheritance:
Inheritance is the process by which objects of one class can share the properties of objects of
another class. It supports the concept of hierarchical classification.
Property inheritance
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
classes.
The real appeal and power of the inheritance mechanism is that it allows the programmer to
reuses class that is almost but not exactly what he wants and to tailor the class in such a way
that it does not introduce any undesirable size effects into the rest of class.
❖ Polymorphism:
Polymorphism means ‘one name with multiple methods.’ The concept of polymorphism is
implemented using the overloaded functions and operators. There are two types of
polymorphism first one is compile time polymorphism and second is run-time polymorphism.
Operator Overloading means an operator to exhibit different behaviors in different
instances is known as operator overloading.
Function overloading means multiple functions with single name to perform different types
of tasks are known as function overloading.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 5 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
The following figure shows the idea of polymorphism
Shape
Draw()
circle box triangle
Draw(circle) Draw(box) Draw(triangle)
Polymorphism
❖ Dynamic binding:
Dynamic binding is also known as late binding or run time polymorphism. Dynamic
binding means to determine to call the function at run time. Dynamic binding is
normally related with inheritance and polymorphism. C++ has virtual functions to
support this. Because dynamic binding is flexible, it avoids the drawbacks of static
binding, which connected the function call and definition at build time.
❖ Message Passing:
Objects are responsible to send and receive information through function calling which is
known as message passing or message communication. Message passing involved the
name of the object, the name of the function and the information to be sent.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 6 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.4 Explain structure of C++ Program
Normally, C++ program files contain four sections as shown in the following image. These
sections are combined into single file or may be placed into separate files and then compiled
independently or jointly.
Structure of C++ Program
The first section is header file section. Some header files are necessary to include before
declaration of class. It normally helps to perform to collect data (input though keyboard) and
display data (output on screen). The second section is class declaration. Class definition
decide building of program or creation of program. Third section is member function
definition and it defines functionality of functions of class. Fourth section is main function
and it is beginning of program. Normally we declare an object of class in main function.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 7 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.5 What are Data types in C++? Explain in details
➢ Data Type:
A data type defines a set of values that a variable can store along with a set of operations that
can be performed on that variable. Common data types are integer, character, and real.
Although C has five basic built-in data types, it is not a strongly typed language, as are Java,
and Python. C language permits almost all type conversions.
For example, you may freely intermix character and integer types in an expression. Unlike a
high-level language, C performs almost no run-time error checking.
For example, no check is performed to ensure that array boundaries are not overrun. These
types of checks are the responsibility of the programmer.
Data types in C++ can be classified under the following characteristics shown in the
following image.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 8 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
➢ C++ Data Type’s Size and range:
1. Primary Data Type or Primitive Data Type: Primitive data type means the data types
which are operated at machine level or built-in data types or predefined data types. Some
primitive or primary data types size and range are given here.
Sr.No Data Type Data Size/Bytes Range
1 char 1 -128 to 127
2 unsigned char 1 0 to 255
3 signed char 1 -128 to 127
4 int 2 -32768 to 32767
5 unsigned int 2 0 to 65535
6 signed int 2 -32768 to 32767
7 short int 2 -32768 to 32767
8 unsigned short int 2 0 to 65535
9 signed short int 2 -32768 to 32767
10 long int 4 -2,147,483,648 to 2,147,483,647
11 signed long int 4 -2,147,483,648 to 2,147,483,647
12 unsigned long int 4 0 to 4294967295
13 float 4 3.4E-38 to 3.4E+38 OR
-3.4×10^38 to 3.4×10^38
14 double 8 1.7E-308 to 1.7E+308 OR
-1.7×10^308 to 1.7×10^308
15 long double 10 3.4E-4932 to1.1E +4932 OR
-3.4^4932 to 1.1^4932
Note: The memory size of primary data types may change according to 32- or 64-bit
operating system. we can get the size of data type by using sizeof() operator. We need to pass
the name of data type into sizeof() operator as an argument. For example. cout<<” Size of
integer data type is:” <<sizeof(int);
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 9 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
2. Derived Data Types:
The data types that are derived from the primitive data types or primary data types or basic
data types. There are some derived data types in C++ language:
1. Function
2. Array
3. Pointer
4. Reference
3. Reference:
Reference is a derived data type in C++. It is an alias or alternative name of an existing
variable. We can manipulate the variable directly. It can not be null. A variable can be
declared as reference by putting ‘&’ in the declaration. Consider following syntax and
example.
Syntax:
data_type & reference variable name=variable;
Example;
#include <iostream>
int main()
{
int x = 100; //non-reference variable
// Reference Derived Type ref variable is a reference to x.
int & ref = x; //reference variable
// Value of x is now changed to 200
ref = 200;
cout << "X = " << x << endl;
// Value of x is now changed to 300
x = 300;
cout << "ref = " << ref << endl;
return 0;
}
Output:
X=200
ref=300
Explanation: ref is a reference variable of variable x. if the value of ref is changed then
value of x is also changed and vice versa.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 10 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.6 What is C++ Constant or const keyword? Explain in brief.
We can fix the value. It means value can not be changed. Constant is used to fix the value
and const is a keyword which is used in C++ to fix the value. There are normally two
types of constant. Look at the following example.
Example 1:
Syntax: const datatype variable name=value;
const float pi=3.14;
const int x=1000;
Example 2:
Syntax: #define variable name value (Preprocessor concept)
#define pi 3.14
#define x 1000
========================================================
Q.7 Explain C++ Variables:
Variable is a storage space or location that stores the values of given data types. In short, it
refers to a memory region that forms a fundamental unit of storage in a program.
In C++, we can declare variable anywhere in the program. It means variables can be declared
where we use or need. So, it makes program easier to write and reduce the errors because it
helps us to when we scan the code forward or backward in program.
Syntax; data type variable name=value;
For example;
int age=19; [declaration and initialization of variable]
Here int is a data type and age is a variable. 19 is the value to store into variable age.
➢ Rules for naming Variable:
1. Variable names can contain letters, digits and underscores
2. First character of variable name should be start with alphabet or an underscore (_).
Variable name can not be start with digit.
3. Variable names are case-sensitive (Count and count are different variables)
4. Variable names cannot contain whitespaces or special characters like! #, %, etc.
5. Reserved words (such as int, float, char, double, long etc) cannot be used as names
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 11 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.8 What are Operators in C/C++? Explain in details.
C++ has a rich set of operators. All C operators are valid in C++. Operators are symbols that
are used to perform various operations on specified operands and values. Operators in C++
are divided into following categories.
1. Arithmetic Operators (+, -, *, /, %)
2. Increment and decrement operators (++x1/--x1, x1++/x1--)
2. Relational Operators (< , >, <= , >=, !=, ==)
4. Bitwise Operators (& , | , ^ , ~ )
5. Assignment Operators (+=, - =, *= , /=)
6. Ternary or Conditional Operators. (?:)
7. sizeof operator.
❖ Arithmetic Operators
Arithmetic Operators are used in mathematical expressions in the same way that they are
used in algebra. The following tables lists the arithmetic operators.
Operator Result
+ Addition
- Substraction (unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
➢ Arithmetic Assignment Operators:
C++ provides special operators that can be used to combine an arithmetic operation with an
assignment. As you probably know, statements like the following are quite common in
programming.
a=a+3;
In C++, you can rewrite this statement as shown here.
a+=3;
Here is another example,
a=a%2;
Which can be expressed as
a%=2;
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 12 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
There are assignment operators for all of the arithmetic, binary operators. Thus any statement
of the form
var=var op expression;
can be rewritten as
var op=expression;
➢ Increment and Decrement Operators:
The ++ and – are C/C++ increment and decrement operators. They have some special
properties that make them quite interesting. The increment operator increases its operand by
one. The decrement operator decreases its operand by one. In both cases increment or
decrement is always done.
There are two types of increment and decrement operators.
1. Prefix increment or decrement operator (++x1 / --x1)
2. Postfix increment or decrement operator (x1++ / x1--)
1. Prefix increment or decrement operator (++x1 / --x1):
If we use prefix increment or decrement then increment or decrement is done first and then
assign the value to the variable.
For example;
int x1=100;
int ans=++x1;
So, first x1 is incremented by 1 and then after assign value of x1 into ans
1. x1=x1+1; //101
2. ans=x1; //101
2. Postfix increment or decrement operator (x1++ / x1--):
If we use postfix increment or decrement then first assignment is done into variable and then
increment or decrement is done.
For example;
int x1=100;
int ans=x1++;
So, first x1 value is assigned to ans and then x1 is increment by 1.
1. ans=x1; //100
2. x1=x1+1; //101
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 13 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
The following program demonstrates the increment operator.
// Demonstrate ++ and --.
int main()
{
int a = 1;
int b = 2;
int c, d;
c = ++b;
d = a++;
c++;
cout<<"a = " <<a<<endl;
cout<<"b = " <<b<<endl;
cout<<"c = " <<c<<endl;
cout<<"d = "<<d<<endl;
}
Output: a=2
b=3
c=4
d=1
==================================================================
➢ Bitwise Operators:
C/C++ support special operators known bitwise operators for manipulation of data at bit level
either 0 or 1.
Bitwise operator can be applied to the integer types, long, int, short, char and byte. These
operators can’t be applied to float or double data type.
Bitwise operators are use for testing bits, shifting bits to left, shifting bits to right. They are
summarized in the following tables.
Operator Result
~ Bitwise Unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
>> Bitwise Shift Right
<< Bitwise Shift Left
&= Bitwise AND Assignment
|= Bitwise OR Assignment
^= Bitwise Exclusive OR Assignment
>>= Bitwise Shift Right Assignment
<<= Bitwise Shift Left Assignment
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 14 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
❖ The Bitwise Logical Operators:
The Bitwise Logical Operators are &, |, ^ and -. The following table shows the outcome of
each operation. It is remembered that the bitwise operators are applied to each individual bit
within each operand.
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
The Bitwise & (AND)
Bitwise AND operator represented by & or AND. The result of AND operation is 1 if both
bits have values 1(One) otherwise 0 (Zero).
For Ex. If the value of x is 17 and value of y is 28
X=17 -→ 0001 0001 8 bit
Y=28 -→ 0001 1100 8 bit
--------------------------------------------------------------------------------------------
X&Y -→ 0001 0000 8 bit
Decimal: 24 = 16
The Bitwise | Operator (OR)
The Bitwise OR Operator is represented by |. The result of OR operation is 1 (One) at least
one bit has a value 1 (One) otherwise 0 (Zero).
For Ex. If the value of x is 17 and value of y is 28
X=17 -→ 0001 0001 8 bit
Y=28 -→ 0001 1100 8 bit
--------------------------------------------------------------------------------------------------
X|Y -→ 0001 1101 8 bit
Decimal: 24 +23 +22 +20 = 16+8+4+1=29
The Bitwise Exclusive ^ Operator (Exclusive OR)
This operator is represented by ^. The result of exclusive or is 1 (One) if only one of the
bits is 1 (One) otherwise 0 (Zero).
For Ex. If the value of x is 17 and value of y is 28.
X=17 -→ 0001 0001 8 bit
Y=28 -→ 0001 1100 8 bit
--------------------------------------------------------------------------------------
X^Y -→ 0000 1101 8 bit
3 2 0
Decimal: 2 +2 +2 = 8+4+1=13
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 15 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
The Bitwise ~ Operator (NOT)
This operator is represented by ~. This operator is also known as bitwise complement or
unary NOT operator. The result of NOT operator is 1 (one) if bits is 0 (Zero) Otherwise 0
(Zero) if bits is 1 (One).
For Ex. If the value of x is 17.
X=17 -→ 0001 0001 8 bit
--------------------------------------------------------------------------------------------
~X -→ 1110 1110 8 bit
Decimal: 24 + 21 = 16+2 = -18
~x---→ 1110 1110
Step 1: Invert ~x----→ 0001 0001
Step 2: Add 1 --------→ +1
=======
0001 0010
❖ Relational Operators:
The relational operators determine the relationship that one operand has to other. They
determine equality and ordering. The relational operators are shown here:
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
The outcome of these operations is an integer value. The relational operators are most
frequently used in the expression that control the if statement and the various loop statements.
As stated, the result produced by a relational operator is an integer value.
For example, the following code fragment is perfectly valid.
int a=4;
int b=1;
int c=a<b; //c=0
In this case the result of a<b is 0 stored in c.
In C/C++ background, please not the following.
int done;
//……
if(!done) …..// valid in C/C++
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 16 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
❖ The Conditional Operator (? :)
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else statements. This operator is the (?:) and it works in Java much like it does in C, C++ and
C#. The (?:) has this general form:
Syntax: expression1? expression2: expression3
Here, expression1 can be any expression that evaluates to a Boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated.
The result of the? Operation is that of the expression evaluated. Both expression2 and
expression3 are required to return the same type, which can’t be void.
For example,
int i, j, ans;
i=10;
j=20;
ans=(i>j) ? i : j;
When C/C++ evaluates this assignment expression, it first looks at the expression to the left
of the question mark. If i is greater than j then the expression between question mark and
colon is evaluated and used as the value of the entire? expression. If it is not greater than j
then the expression after the colon is evaluated and used for the value of the entire?
expression. The result produced by the? operator is then assigned to ans.
Here, is a program that demonstrate the? operator. It uses it to obtain the largest value
between two variables.
For example,
// Demonstrate?
int main () {
int i, j, k;
i = 10, j=20;
k = i > j ? i : j; // get largest value
cout<<”k=” <<k<<endl;
}
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 17 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.9 What are Operators in C++? Explain in details.
C++ has the following operators.
Sr.No Symbol/Operator Name Meaning
1 << Insertion operator or put to operator
2 >> Extraction operator or get from operator
3 :: Scope resolution operator
4 ::* Pointer-to-member declarator
5 ->* Pointer-to-member operator
6 .* Pointer-to-member operator
7 new Memory allocation operator
8 delete Memory release operator
9 endl Line feed operator or next line operator
10 setw Field width operator
3. Scope Resolution Operator:
➢ :: is known as the ‘Scope Resolution Operator’ has been introduced to access class
member function from outside the class.
➢ This operator is also used for distinguishing class members and defining class methods.
➢ The 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 declaration.
➢ A variable declared inside a block is said to be local to that block.
Declaration:
:: variable-name
This operator allows access to the global version of a variable.
For example;
#include<iostream.h>
#include<conio.h>
int m=10; //global variable
int main() //main () begin
{
int m=20; //m is redeclared, local to main
{ //inner block begins
int k=m;
int m=30; //m declared again, local to inner block
cout<<"\nwe are in inner block;
cout<<"\nk="<<k;
cout<<"m="<<m;
cout<<"::m="<<::m;
} //inner block end
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 18 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
cout<<"\nWe are in outer block";
cout<<"m="<<m;
cout<<"::m"<<::m;
return 0;
} //main() end
Output:
We are in inner block
k=20
m=30
::m=10
We are in outer block
m=20
::m=10
In the above program, the variable m is declared at three places, namely outside the main (),
inside the main() and inside the inner block. It is noted that ::m will always refer to the
global m.
4. Member Dereferencing Operator:
C++ permits us to access the class members through pointers. In order to achieve this,
C++ provides a set of three pointer-to-member operators:
✓ ::* To declare a pointer to a member of a class.
✓ * To access a member using object name and a pointer to that member.
✓ ->* To access a member using a pointer to the object and a pointer to that member.
5. Memory Management Operators:
C Language uses malloc( ) and calloc( ) functions to allocate memory dynamically at run
time and free( ) to free dynamically allocated memory.
We use dynamic allocation techniques when it is not known in advance how much of
memory space is needed.
C++ also supports this feature with the help of unary operator ‘new’ and ‘delete’ that perform
the task of allocating and freeing the memory.
An object created with ‘new’ keyword will remain exist until it is destroyed using ‘delete’.
Thus, the lifetime of an object is directly under our control and is unrelated to the block
structure.
Syntax for new :
✓ pointer – variable = new data-type;
The pointer variable is a pointer of type data-type. The new operator allocated sufficient
memory to hold a data object of type data and returns the address of the object. The data-type
may be any valid data type.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 19 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
For example
p = new int;
q = new float;
Where p is pointer of type int and q is pointer of type float.
We can also initialize value while allocating memory.
Syntax: - data-type pointer–variable = new data-type (value);
Example: - int *p = new int (25);
We can allocate memory for any data type including user defined variables like union,
structures and classes with the help of ‘new’ keyword. The general form for one-dimensional
array is:
Syntax: - pointer-variable = new data-type [size];
Example: - int *p = new int[25];
Creating multidimensional array using new :
int *p = new int[3][5][4]; //valid
int *p = new int[3][5][ ]; //invalid
int *p = new int[m][5][4]; //valid
When data is no longer needed it is destroyed to release the memory space for reuse.
The general form of delete operator is:
Syntax: - delete pointer-variable;
Example: - delete p;
The pointer variable is the pointer that points to a data created with new.
If we want to free a dynamically allocated array, we must use the following form of delete:
delete [size] pointer-variable;
The size specifies the numbers of elements in the array to be freed.
delete [ ] p;
This is also valid when there is not sufficient memory new returns NULL pointer.
Advantages of new over malloc( ):
1. It automatically computes the size of the data object. We need not use the operator
sizeof ( ).
2. It automatically returns the correct pointer type, so that there is no need to use a
type cast.
3. It is possible to initialize the object while creating the memory space.
4. Like any other operator, ‘new’ and ‘delete’ can be overloaded.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 20 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.10 Explain Input/output statements:
➢ Input statement: The statement cin>>number1; is an input statement. It also waits for
user to input a number. Here, number1 is a variable and cin (pronounced ‘C in’) is a
predefined object in C++ that corresponds to standard input stream. The operator >> is
known as extraction operator or get from operator. It extracts or takes value from
keyboard and assigned that value to the variable. This operator (>>) is similar to scanf()
function in C-language. This operator can be overloaded. Look at the following figure.
Figure 1: Input data from keyboard using extraction operator (>>)
➢ Output statement:
The statement cout<<” Luck is always with him who work hard”; is an output statement
which is responsible to display an output on screen. The output information should be within
quotation (“”) mark. The identifier cout (pronounced ‘C out’) is a predefined object that
represents the standard output stream in C++. Here the standard output stream or statement
represent in the Figure 2. The operator << is called the insertion operator or put to
operator. It inserts or sends the values of the variable to the object and object enable to
display value on screen.
Figure 2: Output data using insertion operator.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 21 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
➢ Q.11 Explain Comment in C++:
There are two types of comments in C++. First is a single line comment and second is a
multiline comment.
1. Single line comment (//):
Comments start with double slash symbol (//) and terminate at the end of the line. A comment
may start anywhere in the line and whatever we have written inside double slash symbol will
be ignored by compiler. Double slash symbol is a normally single line comment.
For example;
// include header file
// variable declaration
// input data
// output or display data.
2. Multi line comment (/*-------*/):
When we want to make comment for multi-line, we can use symbol like (/*--------*/). The
following is an example of multiline comment.
/*
This is an example of program which determine whether the given number is odd,
even, prime number, square root or not.
*/
==================================================================
Q.12 What is class and object? How to declare & Create class and object in C++?
class: class is a single unit which combines data members and member function together.
Class variable is known as object. When we create a class, we are creating a new abstract
data type that can be treated like any other built-in data type.
Generally, C++ class has two following specifications.
1 class declaration
2 class function declaration and definition.
The class declaration describes the type and scope of its members. The class functions
definitions describe how the class functions are implemented.
Syntax: class declaration
class classname
{
private:
data member declaration or variable declaration;
function declaration;
public:
data member declaration or variable declaration;
function declaration;
protected:
data member declaration or variable declaration;
member function declaration;
};
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 22 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
The class declaration is similar to structure declaration in c-language. The class defines user
defined data types. It ends with semicolon with closing brace (}). The class body contains
two parts variables and functions. Variables are known as data member of class and
functions are known as member function of class. Both are combinedly known as data
members of class.
We can declare both data members and member function either in private or public section.
The keyword private and public are known as visibility levels.
➢ Private Members: The class members which are declared as private can only accessible
from within class only. Data hiding is an essential feature of OOP or C++. It can be done
by using private accessibility. It is the by default access specifier in C++. Private is an
optional keyword in C++. If both labels are missing, by default all members are private.
➢ Public Members: The class members which are declared as public can accessible from
outside class also.
➢ Example on Class Declaration and Definition:
class student
{
private:
int rollno, sub1, sub2, sub3, total;
char name[30];
char mobileno[12];
float per;
public:
void getdata();
void calresult();
void putdata();
};
In above example, class name is student and it contains data members like rollno, name,
mobileno, sub1, sub2, sub3, total and per. All data members are private and therefore it is
only accessible from class functions only, not outside class.
In above example, there are three member functions which are getdata(), calresult() and
putdata(). All these member functions are public and therefore it is accessible from outside
class.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 23 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.13 How to define an Object of Class or How to define an object? Explain
Class variable is known as an object. Class is a logical structure of program and object is a
physical structure of program. We can declare an object similar as like to declare variable of
any inbuilt data type. For example
class: STUDENT STUDENT
getdata()
DATA
rollno
name
mobileno
………………… putdata()
FUNCTIONS
getdata()
putdata()
………….
…………. .....................
❖ Representation of a class
❖ Creation or Declaration of object:
Syntax: classname variable name;
Example: student s1; // s1 is an object. It has memory.
Here, s1 is an object. We may also declare more than one object in one statement. For
example;
student s1, s2, s3; //multiple object creation
The declaration or creation of an object is similar to any basic data type. The necessary
memory space is allocated to an object during its declaration. Class is similar to structure in
c-language and it just like a template. It does not create any memory space for the objects.
Objects can also be created when defined a class by placing name immediately after the
closing brace as we do in the case of structure in c-language. For example;
class student
{
int rollnono;
char name[30];
public:
void getdata();
void putdata();
}s1,s2,s3;
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 24 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.14 How to accessing class members? Explain
As we know that, public members can accessible from outside class while private members
can not accessible from outside class. It is only accessible from within class members only.
The following is the format to calling the functions.
Syntax:
return type variable name= object_name.function-name(arg1, arg2,arg3….argn);
For example;
s1.getdata();
s1.mark(78,90,93);
s1.putdata();
❖ In above example, getdata() function is used to get the values from user or keyboard.
Second function mark (78,90,93), we can pass the value 78, 90, 93 to corresponding
variable. Third function putdata() is display the output of program.
❖ We can access class data member by an object of class as like to access member function
if data member is public. Private data member cannot be accessible by an object.
For example;
class student
{
private:
int rollno;
char name[30];
char gender;
public:
char course[30];
void getdata(int, char );
void calresult();
void putdata();
};
void main()
{
student s1;
s1.rollno=101; //invalid, because rollno is private
strcpy(s1.name, ”Suraj”); //invalid, because name is private.
strcpy(s1.course,”B.C.A”); //valid, because course is public.
}
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 25 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
Q.15 How to defining member functions? Explain
Member functions can be defined into two places;
1. Outside the class definition
2. Inside the class definition
1. Outside the class definition:
Member functions can be declared inside or outside class. Member functions definitions are
very much similar to normal functions. Member functions should have header and a function
body. The main difference between normal function and member function is that member
functions have identity label of class where it is declared. So, identity labels tell compiler
which class the functions belongs to. The general syntax of function definition from outside
class is given here.
Syntax of member functions definition:
return type class name :: function name (argument declaration)
{
//Function body
}
For example; consider the member functions getdata(int, char) and putdata() as we have seen
in above example;
void student :: getdata(int r, char g)
{
rollno=r;
gender=g;
}
void student :: putdata()
{
cout<<”Rollno:”<<rollno<<endl;
cout<<”Name:”<<name<<endl;
cout<<”Gender:”<<gender<<endl;
}
➢ Characteristics of Member Functions:
1. Several different classes can use the same function name. The membership label will
resolve their scope.
2. Member functions can access the private data of the class. A non-member functions
cannot do so.
3. A member function can call another member function directly without using dot operator.
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 26 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
2. Inside the class definition
We can define the member functions inside the class. When we define functions inside the
class, it is treated as inline function. Therefore, all the restrictions and limitations that apply
to an inline function are also applicable here. Normally, small functions are defined inside the
class definition.
Look at the following example, as we could define inside the member functions of student
class.
class student
{
int rollno;
char name[30];
char gender;
public:
void getdata(int r, char g)
{
rollno=r;
gender=g;
}
void putdata()
{
cout<<”Rollno:”<<rollno<<endl;
cout<<”Name:”<<name<<endl;
cout<<”Gender:”<<gender<<endl;
}
};
==================================================================
❖ A C++ program with Class:
All the details discussed far now are implemented in the following program.
class student
{
int rollno; //private data member
char gender; //private data member
public:
char name[30]; //public data member
void putdata(); //public member functions
//Member function definition inside the class. So function become inline function
void getdata(int r, char g) //public member functions
{
rollno=r;
gender=g;
}
};
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 27 of 28
Shree Swaminarayan College of Computer Science, Sardarnagar, Bhavnagar
305. Object Oriented Programming (OOP) USING C++ I Unit-1
//Member function definition outside the class
void student:: putdata()
{
cout<<”Rollno:”<<rollno<<endl;
cout<<”Name:”<<name<<endl;
cout<<”Gender:”<<gender<<endl;
}
// Main program starts
void main()
{
student s1, s2; //object creation s1 and s2
s1.getdata(101, 'M'); //call member function getdata() with argument
strcpy("Akshat",s1.name); //copy name (data member)
s1.putdata(); //call member function putdata() without argument.
s1.getdata(102,'F'); //call member function getdata() with argument
strcpy("Nitya", s1.name); //copy name (data member)
s1.putdata(); //call member function putdata() without argument.
}
Prepared By: Gaurang Bhatt B.C.A-Sem-3 Page 28 of 28