You are on page 1of 74

Lecture 2

OOP
OOP Approach

• The fundamental idea behind object-oriented


language is to combine into a single unit both
– data and
– the functions that operate on that data.
• Such a unit is called an object
Object Oriented Programming (OOP) Paradigm

• “Object Oriented programming is an approach of problem solving where


all computations are carried out using objects”

• Object?
Object –identical unit
Attributes & Behaviors in OOP

• Almost any noun can be reasonably represented as a


software object in terms of
– attributes (e.g., name, color and size)
– and behaviors (e.g., calculating, moving and
communicating).
Static Properties
Dynamic properties
Class

• Take a minute and think about what do you understand when you hear the
word “chair”

• We know that chairs have properties like :


– seating capacities,
– back,
– number legs
– shape
– color
– a degree of softness and so on so forth
Example (Chair as an Object)

• The idea of the chair allows you to recognize a chair. However, the definition does not exist

• However, if you look around the room, there are several chairs are in the room, and each
chair is an object. Each of these objects is an example of that thing called the Chair (class)

• A class is a description of a kind of thing.


• An object is an actual thing
Class
Class
Class
Concept of a “Class” in OOP

•A key aspect of Object Oriented Programming is the


use of Classes
• A class is a specification/model of an object
• You can “think of a class as a concept” and an
object as “Realization of that concept”
Objects

• The world is full of objects


• Many objects have always existed. New objects come to existence and
others cease to exist
•Remember: A CLASS is ONLY a definition. It describes a
set of qualifiers that describe what the objects that
belong to that class look like

•The things that are tangible and exist are the


Objects. Objects may belong to a classifcation
What is an Object in OOP ?

• Objects have properties also called as


attributes
• Tasks performed by an object are expressed as methods
OOP: Real World Modeling

• Identify objects that the problem is concerned with,


• – e.g. Sports Application (Sportsman would be the object),

• Produce a detailed design for each new data type (Objects) including
the operations that can be performed on each object
• Express logic of your program in terms of objects and kinds of
operations they allow
Class

•A class defines the abstract characteristics of a group of similar objects


• Attributes(fields or properties)
• Behaviors(methods or functions).
• A class is a user-defined type.
• A class is a blueprint or template to build a specific type of object
• Every object is built from a class.
• Can be used to create objects: Variables of the class type
Class
vs.
Objects
C++ Class – Declaration

• To declare a class
• – The class keyword is used
• The declaration is enclosed in braces {};
• The class definition ends with a semicolon
• Every piece of code inside the braces is called ‘class body’
• The class body thus contains class members
C++ Class – Declaration

•Class classname
•{
•………….
•…………
•…………….

•};
C++ Class – Declaration
• Every piece of code inside the braces is called ‘class body’

Classes
(Templates
)

Attributes
Behaviors
C++ Class – Declaration

Classes
(Templates
)

Data
Functions
C++ Class – Declaration

Classes
(Templates
)

Data Members
Class
Members
Member Functions
Class

– Data Members define Object attributes


– Member Functions define Object Behavior

• “Class” is an Object-Oriented Programming Concept


Class

•Class Student
•{
– Attributes
• Roll number
• Name
• Marks
– Behavior:
• Curricular performance
• Extra curricular performance
•} ;
Class
C++ Class – Data Members

• A data member can be of any valid C++ data type. For


example
– Ordinary variable – primitive type
– An instance variable of another class –
programmer defined type
– A pointer or reference variable
C++ Access Modifiers

• Three types of Access Modifiers:


• private:
• public:
• protected:
• The scope of an access modifier continues until another access modifier
is mentioned explicitly
• There is a colon after every access modifier
C++ Access Modifiers

• class Base {
• public:
• // public members go here
• protected:
•// protected members go here
• private:
• // private members go here
•};
public:

• Public members can be accessed by member functions as well


as by functions that declare the objects of that class.
• Normally, for classes, those member functions are made public
which must interact with the outside world.
private:

• Private members can only be accessed by member functions.


• – This means they can only be accessed in the member function body.
• Remember the ‘members’ mean both variables and functions.
• By default all class members are private, unless declared otherwise.
A Sample C++ Program

• A simple C++ program begins this way


#include <iostream>
using namespace std;
int main()
{

• And ends this way


return 0;
}
Parts of Program

Line Comment
// sample C++ program
Pre processor
#include <iostream>
directive
Which
using namespace std; namespace to
int main() use
Main function
{ beginning
beginning of
cout << "Hello, there!"; block for main

return 0;
}
Ending of block
for main
Comments

• Document programs
• Improve program readability
• Ignored by compiler
• Single-line comment: Begin with //
• Multiple-line comment: Begin with /* and end with */

// sample C++ program


/* sample C++
program */
Pre Processor Directive

// sample C++ program


Pre processor
#include <iostream> directive
using namespace std;
int main()
{
cout << "Hello, there!";
return 0;
}
Directives

• Lines beginning with a hash sign (#) are directives read and
interpreted by what is known as the preprocessor.
• They are special lines interpreted before the compilation of the
program itself begins.
# include

• Both the user and the system header files are included using the
preprocessing directive #include. It has the following two forms −
• #include <file>
• #include "file"
# include <file>, "file"

• #include <file> This form is used for system header files. It


searches for a file named 'file' in a standard list of system
directories.
• #include "file" This form is used for header files of your own
program. It searches for a file named 'file' in the directory
containing the current file.
#include <iostream>

• Directive #include <iostream>, instructs the


preprocessor to include a section of standard C++
code, known as header iostream, that allows to
perform standard input and output operations,
such as writing the output of this program (Hello
World) to the screen.
The Using Directive

• using namespace std;

• A C++ program can be divided into different namespaces.

• A namespace is a part of the program in which certain names are


recognized; outside of the namespace they’re unknown.

• Various program components such as cout are declared within this


namespace. If we didn’t use the using directive, we would need to add
the std name to many program elements. For example, in our example
program we’d need to say
• std::cout << “Hello World”;
C++ Program

Some common elements in programming languages

1. Key Words
2. Programmer-Defined Identifiers
3. Operators
4. Punctuation/Separators
5. White Space
Keywords

• Also known as reserved words


• Have a special meaning in C++
• Can not be used for any other purpose
• Key words in the example program
• main
• using
• namespace
Identifier
Names made up by the programmer. An
identifier is the name used to denote labels,
types, variables, constants or functions, in
a C++ program.
• C++ is a case-sensitive language.
– Work is not work

• Identifiers should be descriptive


– Using meaningful identifiers is a good
programming practice
Rules for Identifiers
• Identifiers must be unique
• Identifiers cannot be reserved words (keywords)
– int main return
• Identifier must start with a letter or underscore,
and be followed by zero or more letters (A-Z, a-z),
digits (0-9), or underscores
• After the first character you may use alphabetic
characters, numbers, or underscore characters.
• Upper- and lowercase characters are distinct
Rules for Identifiers

• VALID
age_of_dog _taxRateY2K PrintHeading
ageOfHorse
• NOT VALID
age# 2000TaxRate Age-Of-Dog main
Identifiers..
Stream Operators – Input and Output

• C++ treats input and output as a stream of characters.


• stream : sequence of characters (printable or nonprintable)
• The functions to allow standard I/O are in iostream header file or
iostream.h.
• Thus, we start every program with
#include <iostream>
using namespace std;
Escape Sequences

• The backslash (\) is called the escape character.


• It tells the compiler that the next character is “escaping” it’s
typical definition and is using its secondary definition.
• Examples:
• new line: \n
• horizontal tab: \t
• backslash: \\
• double quote \”
Escape Sequences

Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.
Output Statements (Expression)

• All expressions are computed and then output.


cout << “The answer is ” << 3 * 4 ;
OUTPUT: The answer is 12
Input Statements

int num;
cout<< “Enter number\n \n”;
cin >> num;
52 Punctuation
• Characters that mark the end of the program.
• Characters that separate items in the list.
• Characters use for scope resolution
• types of punctuation marks

,
;
:
Variables

• A variable is a memory address (placeholder)


where data can be stored and changed.
• Declaring a variable means specifying both its
name (identifier) and its data type.
• Defining/initializing a variable means giving the
variable a value.
• When new value placed into variable, overwrites
previous value
Sample Program
#include <iostream>
using namespace std;
class cars
{
public:
int c_model()
{
cout << "Enter your car model";
cin >> c_modelNo;
return c_modelNo;
}
private:
int c_modelNo;
};
Sample Program

int main()
{
cars a;
int x,y;
x = a.c_model();
cout << x; Output?
cout << a.c_modelNo;
}
Object initialization

• When you declare an object in main it is called object initialization.


class cars
{
---------
};
int main()
{
cars a; //initialization
}
How to access class members?

• The dot member selection operator (.) is combined with an object’s


name to access class members.

class cars
{
int c_modelNo();
};
Object’s name.class member
cars a;
a.c_modelNo();
Class Scope

• The class scope will be


• Data members declared in class definition/body
• Member Functions declared in class definition
Within class, class members are immediately accessible by
all of class’s member functions
Tell me?

• What if a variable is defined in class and in a


member function of the class with the same
name!
How a member function will use both variables or
is it possible to do so?
Scope resolution Operator


Scope resolution operator is denoted with “::”
• Also called binary Scope resolution operator.
• This is used to refer any Data member of the class or Member
Function of the class.
Scope resolution Operator

• Just declared the member function in the class but


definition is not required at the moment.
• Can later define a member function outside the class in
same file using scope resolution operator.
• This member function will be still in the class scope.
• It can be accessed only by using the reference of the
class object.
Example for scope resolution operator

class cars
{
int car_modelNo();
}

int cars::car_modelNo()
{
---------
}
Question!

•How a member function will use


both variables with same name
or is it possible to do so?
Inline Functions

• Inline functions are a C++ enhancement feature to increase the


execution time of a program
• Functions can be instructed to compiler to make them inline
• Compiler replaces the definition of inline functions at compile
time instead of referring function definition at runtime
Inline Function Note!

• This is just a suggestion to compiler to make the function inline


• If function is big (in term of executable instruction etc) then,
compiler can ignore the “inline” request
• Treat the function as normal function
• Member functions defined inside the class body are automatically
inlined however compiler reserves the right to take it as inline or
not.
How to make inline function

• To make any function as inline, start its definitions with the keyword “inline”.
class cars
{
int car_modelNo();
}

inline int cars::car_modelNo()


{
---------
}
Why to use inline?

•  functions for small work


• calling overhead each time they are being called
• stores the memory address of the instructions
•  loads the function being called into the memory
• copies argument values
• stores the return value of the function
• etc
• Too much run time overhead
Inline functions

• With inline keyword, the compiler replaces the function call


statement with the function code itself (process called expansion)
and then compiles the entire code
• No need to jump to load all necessary data/instructions
inline Functions

• It speeds up your program by avoiding function calling overhead


But
• It increases the executable size due to code expansion.

• When to use inline functions?


• Use inline function when performance is needed
• Compiler may or may not inline the functions you marked as inline
• It may also decide to inline functions not marked as inline at
compilation or linking time.
Using multiple objects

• Consider registering multiple users using same methods and data


members.
• How will you implement this with classes and objects?
• You can define multiple objects that will response according to
your data.
• For example in class cars
• One object may represent classic cars.
• Other may represent sports cars.
Example of using multiple objects

#include <iostream>
using namespace std;

class queue
{
int qval;
public:
void setval(int v)
{
qval = v;
}

Example….

• int getval()
• {
• return qval;
• }
• };
Example….

• int main()
• {
• queue obj1, obj2;
• obj1.setval(5);
• obj2.setval(6);
• obj1.setval(4);

• cout << obj1.getval()<<" " <<obj2.getval() <<" " <<obj1.getval();


• }
Example…. Output

4 6 4

You might also like