0% found this document useful (0 votes)
110 views

Unit 4 C++ Basic Object Oriented Programming

The document discusses the basics of object-oriented programming in C++. It defines key concepts like objects, classes, encapsulation, inheritance, and polymorphism. It also provides examples of basic C++ code structure and common functions/operators like cout and cin for input/output.
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)
110 views

Unit 4 C++ Basic Object Oriented Programming

The document discusses the basics of object-oriented programming in C++. It defines key concepts like objects, classes, encapsulation, inheritance, and polymorphism. It also provides examples of basic C++ code structure and common functions/operators like cout and cin for input/output.
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/ 16

UNIT 4 C++ BASIC

Object Oriented Programming


“Object oriented programming as an approach that provides a way of
modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies
of such modules on demand”.

Features of the Object Oriented programming


1. Emphasis is on doing rather than procedure.
2. programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are tied together in the
data
5. structure.
6. Data is hidden and can’t be accessed by external functions.
7. Objects may communicate with each other through functions.
8. New data and functions can be easily added.
9. Follows bottom-up approach in program design.

BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING


1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing

Object: - In C++, Object is a real-world entity, for example, chair, car, pen,
mobile, laptop etc.

In other words, object is an entity that has state and behaviour. Here, state
means data and behaviour means functionality.

The fundamental idea behind object-oriented approach is to combine both data


and function into a single unit and these units are called objects.

Class:- A group of objects that share common properties for data part and some
program part are collectively called as class.
In C ++ a class is a new data type that contains member variables and member
functions that operate on the variables.
DATA ABSTRACTION:
Abstraction refers to the act of representing essential features without
including the background details or explanations. Classes use the concept of
abstraction and are defined as size, width 6.-and cost and functions to operate
on the attributes.
DATA ENCAPSALATION:
The wrapping up of data and function into a single unit (called class) is known as
encapsulation. 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 objects data and the program.
POLYMORPHISIM:
Polymorphism means the ability to take more than one form. An operation may
exhibit different instance. The behaviour depends upon the type of data used in
the operation. A language feature that allows a function or operator to be given
more than one definition. The types of the arguments with which the function
or operator is called determines which definition will be used.
INHERITENCE:
Inheritance is the process by which objects of one class acquire the properties
of another class. In the concept of inheritance provides the idea of reusability.
This mean that we can add additional features to an existing class without
modifying it. This is possible by designing a new class will have the combined
features of both the classes.
C++ supports five types of inheritance:
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance
DYNAMIC BINDING:
Binding refers to the linking of a procedure call to the code to the executed in
response to the call. Dynamic binding means the code associated with a given
procedure call is not known until the time of the call at run-time. It is associated
with a polymorphic reference depends upon the dynamic type of that
reference.
MESSAGE PASSING: An object-oriented program consists of a set of objects that
communicate with each other. A message for an object is a request for
execution of a procedure and therefore will invoke a function (procedure) in the
receiving object that generates the desired result. Message passing involves
specifying the name of the object, the name of the function (message) and
information to be sent.

C++ :- C ++ is an object-oriented programming language, C ++ was developed by


Bjorne Stroustrop at AT & T Bell lab, USA in early eighties. C ++ was developed
from c language.

C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.
Comments can be singled-lined or multi-lined.
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not
be executed).
C++ Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
Output Operator: (cout<<) The statement cout <<”Hello, world” displayed the
string with in quotes on the screen. The identifier cout can be used to display
individual characters, strings and even numbers. It is a predefined object
that corresponds to the standard output stream. Stream just refers to a flow of
data and the standard Output stream normally flows to the screen display.
The cout object, whose properties are defined in iostream.h represents that
stream.
The insertion operator << also called the ‘put to’ operator directs the
information on its right to the object on its left.

Input Operator(cin>>) The statement cin>> number 1; is an input statement


and causes. The program to wait for the user to type in a number. The number
keyed in is placed in the variable number1. The identifier cin is a predefined
object in C++ that corresponds to the standard input stream. Here this stream
represents the key board.
The operator >> is known as get from operator. It extracts value from the
keyboard and assigns it to the variable on its right.

STRUCTURE OF C++ PROGRAM


1. Include files
2. Class declaration
3. Class functions, definition
4. Main function program
# include<iostream>
using namespace std;
class person
{
char name[30];
int age;
public:
void getdata(void);
void display(void);
};
void person::getdata()
{
cout<<"enter name";
cin>>name;
cout<<"enter age";
cin>>age;
}

void person::display()
{
cout<<"name:"<<name;
cout<<"age:"<<age;
}

int main( )
{
person p;
p.getdata();
p.display();
return(0);
}

What is a namespace?
Namespaces provide a way of declaring variables within a program that have
similar names. It allows users to define functions with the same name as a
function in a pre-defined library or used-defined functions within main().
Namespaces can also be used to define classes, variable names, and functions.

Namespaces allow us to group named entities that otherwise would have global
scope into narrower scopes, giving them namespace scope. This allows
organizing the elements of programs into different logical scopes referred to by
names.
Namespace is a feature added in C++ and not present in C.
• A namespace is a declarative region that provides a scope to the
identifiers (names of the types, function, variables etc) inside it.
• Multiple namespace blocks with the same name are allowed. All
declarations within those blocks are declared in the named scope.
• A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
namespace namespace_name
{
int x, y; // code declarations where
// x and y are declared in
// namespace_name's scope
}
• Namespace declarations appear only at global scope.
• Namespace declarations can be nested within another namespace.
• Namespace declarations don’t have access specifiers. (Public or private)
• No need to give semicolon after the closing brace of definition of
namespace.
• We can split the definition of namespace over several units.

Example :

#include <iostream>
using namespace std;

namespace foo
{
int value()
{
return 5;
}
}

namespace bar
{
const double pi = 3.1416;
double value()
{
return 2*pi;
}
}

int main () {
cout << foo::value() << '\n';
cout << bar::value() << '\n';
cout << bar::pi << '\n';
return 0;
}

Namespace aliasing
Existing namespaces can be aliased with new names, with the following syntax:

namespace new_name = current_name;

The std namespace


All the entities (variables, types, constants, and functions) of the standard C++
library are declared within the std namespace. Most examples in these tutorials,
in fact, include the following line:

using namespace std;

TOKENS:
The smallest individual units in program are known as tokens. C++ has the
following tokens.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators

KEYWORDS:
Keywords are those words whose meaning is already defined by Compiler.
These keywords cannot be used as an identifier. Note that keywords are the
collection of reserved words and predefined identifiers. Predefined identifiers
are identifiers that are defined by the compiler but can be changed in meaning
by the user.
There are a total of 95 reserved words in C++. The reserved words of C++ may
be conveniently placed into several groups. In the first group, we put those that
were also present in the C programming language and have been carried over
into C++. There are 32 of these.

Here is a list of all these reserved words:


alignas (since C++11) double reinterpret_cast
alignof (since C++11) dynamic_cast requires (since C++20)
and else return
and_eq enum short
asm explicit signed
atomic cancel (TM TS) export (1) sizeof(1)
atomic commit (TM TS) extern (1) static
atomic_noexcept (TM TS) false static_assert (since C++11)
auto (1) float static_cast
bitand for struct(1)
bitor friend switch
bool goto synchronized (TM TS)
break if template
case import (modules TS) this
catch inline(1) thread_local (since C++11)
char int throw
char16_t (since C++11) long true
char32_t (since C++11) module (modules TS) try
class(1) mutable(1) typedef
compl namespace typeid
concept (since C++20) new typename
const noexcept (since C++11) union
constexpr (since C++11) not unsigned
const_cast not_eq using(1)
continue nullptr (since C++11) virtual
co_await (coroutines TS) operator void
co_return (coroutines TS) or volatile
co_yield (coroutines TS) or_eq wchar_t
decltype (since C++11) private while
default(1) protected xor
delete(1) public xor_eq
do register(2)

IDENTIFIERS:
Identifiers refers to the name of variable, functions, array, class etc. created by
programmer. Each language has its own rule for naming the identifiers.
The following rules are common for both C and C++.
1. Only alphabetic chars, digits and underscore are permitted.
2. The name can’t start with a digit.
3. Upper case and lower-case letters are distinct.
4. A declared keyword can’t be used as a variable name.

Variable
A variable is a name given to a memory location. It is the basic unit of storage in
a program.

• The value stored in a variable can be changed during program execution.


• A variable is only a name given to a memory location, all the operations
done on the variable effects that memory location.
• In C++, all the variables must be declared before use.

A typical variable declaration is of the form:


// Declaring a single variable
type variable_name;

// Declaring multiple variables:


type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers
and the underscore ‘_’ character. However, the name must not start with a
number.

Constant: Whose value fix during the execution of programme in known as


constant
The const Keyword
You can use const prefix to declare constants with a specific type as follows −

const type variable = value;

Literals: The type of constant is known as literals

There are some literals:

Integer Constants
As the name itself suggests, an integer constant is an integer with a fixed value,
that is, it cannot have fractional value like 10, -8, 2019.
For example,

const int limit = 20;

Floating or Real Constants


We use a floating-point constant to represent all the real numbers on the
number line, which includes all fractional values. For instance,
const long float pi = 3.14159;
We may represent it in 2 ways:
• Decimal form: The inclusion of the decimal point ( . ) is mandatory.
For example, 2.0, 5.98, -7.23.
• Exponential form: The inclusion of the signed exponent (either e or E) is
mandatory.
For example, the universal gravitational constant G = 6.67 x 10-11 is
represented as 6.67e-11 or 6.67E-11.
Character Constants
Character constants are used to assign a fixed value to characters including
alphabets and digits or special symbols enclosed within single quotation marks( ‘ ’
).
Each character is associated with its specific numerical value called the ASCII
(American Standard Code For Information Interchange) value.

For example, ‘+’, ‘A’, ‘d’.

String Constants

A string constant is an array of characters that has a fixed value enclosed within
double quotation marks ( “ “ ).

For example, “DataFlair”, “Hello world!”

Boolean Literals

There are two Boolean literals and they are part of standard C++ keywords −

• A value of true representing true.

• A value of false representing false.

You should not consider the value of true equal to 1 and value of false equal to 0.
Operator In C++
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Arithmetic Operators They are the types of operators used for
performing mathematical/arithmetic operations. They include:

Operator Description

+ addition operator Adds to operands.

- subtraction operator Subtracts 2nd operand from 1st operand.

* multiplication operator Multiplies 2 operands.

/ division operator. Divides numerator by denominator.

% modulus operator Returns remainder after division.

++ increment operator Increases an integer value by 1.

-- decrement operator. Decreases an integer value by 1.

Relational Operators
These types of operators perform comparisons on operands. For
example, you may need to know which operand is greater than the
other, or less than the other. They include:

• == equal to operator. Checks equality of two operand values.


• != not equal to operator Checks equality of two operand
values.
• > great than operator Checks whether value of left operand is
greater than value of right operand.
• < less than operator. Checks whether value of left operand is
less than value of right operand.
• >= greater than or equal to operator Checks whether value of
left operand is greater than or equal to value of right operand.
• <= less than or equal to operator. Checks whether value of left
operand is less than or equal to value of right operand.

Logical Operators
The logical operators combine two/more constraints/conditions.
Logical operators also complement evaluation of original condition
under consideration. They include:
&& logical AND operator. The condition is true if both operands are
not zero.
|| logical OR operator. The condition is true if one of the operands is
non-zero.
! logical NOT operator. It reverses operand's logical state. If the
operand is true, the ! operator makes it false.

Bitwise Operators
Bitwise operators perform bit-level operations on operands. First,
operators are converted to bit level then operations are performed
on the operands. When arithmetic operations like addition and
subtraction are done at bit level, results can be achieved faster. They
include:
• & (bitwise AND). It takes 2 numbers (operands) then performs
AND on each bit of two numbers. If both are 1, AND returns 1,
otherwise 0.
• | (bitwise OR) Takes 2 numbers (operands) then performs OR
on every bit of two numbers. It returns 1 if one of the bits is 1.
• ^ (the bitwise XOR) Takes 2 numbers (operands) then
performs XOR on every bit of 2 numbers. It returns 1 if both bits
are different.
• << (left shift) Takes two numbers then left shifts the bits of
the first operand. The second operand determines total places
to shift.
• >> (right shift) Takes two numbers then right shifts the bits of
the first operand. The second operand determines number of
places to shift.
• ~ (bitwise NOT). Takes number then inverts all its bits.

Assignment Operators
Assignment operators assign values to variables. The operand/variable is added
to left side of the operator while the value is added to the right side of the
operator. The variable and the value must belong to the same data type,
otherwise, the C++ compiler will raise error. For example:

x = 5;

In the above example, x is the variable/operand, = is the assignment operator


while 5 is the value. Here are the popular assignment operators in C++:

sizeof operator
This operator determines a variable's size. Use sizeof operator to determine the
size of a data type. For example: sizeof(int)

Conditional Operator/ ternary operator


This operator evaluates a condition and acts based on the outcome of
the evaluation.
Condition ? Expression2 : Expression3;
Parameters:

• The Condition is the condition that is to be evaluated.


• Expression1 is the expression to be executed if condition is true.
• Expression3 is the expression to be executed if condition is false.

Some Other Operators in C++

• << insertion operator


• >> extraction operator
• :: scope resolution operator
• : :* pointer to member declarator
• * pointer to member operator
• .* pointer to member operator
• Delete memory release operator
• Endl line feed operator
• New memory allocation operator
• Setw field width operator

Data Type in c++


Variables are used to represent reserved memory locations that is used to store
values, when we create a variable we are a suppose to allocate some memory
space for that variable. C++ is a statically typed programming language. This
means that variables always have a specific type and that type cannot change.
Every variable have data type associated to it, data type for a variable defines –

1. Primary(Built-in) Data Types:

• character
• integer
• floating point
• boolean
• double floating point
• void
• wide character

2. User Defined Data Types:


• Structure
• Union
• Class
• Enumeration
• Array
• Pointer
• Reference

You might also like