Download presentation
Presentation is loading. Please wait.
Published byGyles Edwin Hawkins Modified over 7 years ago
1
Introduction to Object Oriented Programming
Raju Pal Assistant Professor JIIT, Noida
2
Topics Covered Comparison of Procedural and Object Oriented Approach
Principles of Object-Orientation Objects Classes Internal representations of Objects
3
Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming
The unit in procedural programming is function, and unit in object-oriented programming is class Procedural programming concentrates on creating functions, while object-oriented programming starts from isolating the classes, and then look for the methods inside them. Procedural programming separates the data of the program from the operations that manipulate the data, while object-oriented programming focus on both of them
4
Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming
5
Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming
6
Example “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and transfer money between accounts”
7
Procedural Approach Focus is on procedures
bool MakeDeposit(int accountNum,float amount); float Withdraw(int accountNum,float amount); struct Account { char *name; int accountNum; float balance; char accountType; }; Focus is on procedures All data is shared: no protection More difficult to modify Hard to manage complexity
8
Object Oriented Approach
Data and operations are grouped together class Account { public: float withdraw(); void deposit(float amount); private: float balance; ); Account Withdraw Deposit Transfer
9
Object Oriented Approach
Protection Consistency Allows change
10
Procedural vs. Object-Oriented
Withdraw, deposit, transfer Object Oriented Customer, money, account
11
Topics Covered Comparison of Procedural and Object Oriented Approach
Principles of Object-Orientation Objects Classes Internal representations of Objects
12
Object Oriented Programming
As softwares became increasingly complex, manageability often became a concern. The OOP paradigm focuses on data rather than processes, with programs composed of self-sufficient modules ("classes"), each instance of which ("objects") contains all the information needed to manipulate its own data structure ("members").
13
Object Oriented Programming
What is Object? An object is anything that can be represented by data in a computer’s memory and manipulated by a computer program. is an instance of a class. Each object has a class which defines its data and behavior Collection of data and methods. What is Class? Refers to a blueprint. A class is a description of a set of objects that share the same attributes, operations, relationships, and semantics. It defines the variables and methods the objects support. Also called Data type of object.
14
Object Oriented Programming
What is obect oriented? Each object knows its own class. An object-oriented program may be viewed as a collection of interacting objects, as opposed to the conventional model, in which a program is seen as a list of tasks (subroutines) to perform
15
Principles of OOP Inheritance Abstraction Polymorphism Encapsulation
16
Topics Covered Comparison of Procedural and Object Oriented Approach
Principles of Object-Orientation Objects Classes Internal representations of Objects
17
What Is an Object? Informally, an object represents an entity, either physical, conceptual, or software. Physical entity Conceptual entity Software entity Truck Objects allow the software developer to represent real-world concepts in their software design. These real-world concepts can represent a physical entity such as a person, truck, or space shuttle. Objects can be concepts like a chemical process or algorithms. Object can even represent software entities like a linked list. Chemical Process Linked List
18
A More Formal Definition
An object is an entity with a well-defined boundary and identity that encapsulates state and behavior. State is represented by attributes and relationships. Behavior is represented by operations, methods, and state machines. Attributes An object is an entity that has a well-defined boundary. That is, the purpose of the object should be clear. An object has two key components: attributes and operations. Attributes represent an object’s state, and operations represent the behavior of the object. Object behavior and state are discussed in the next few slides. Object Operations
19
An Object Has State The state of an object is one of the possible conditions in which an object may exist. The state of an object normally changes over time. The state of an object is one of the possible conditions that an object may exist in, and it normally changes over time. The state of an object is usually implemented by a set of properties called attributes, along with the values of the properties and the links the object may have with other objects. State is not defined by a “state” attribute or set of attributes. Instead, state is defined by the total of an object’s attributes and links. For example, if Professor Clark’s status changed from Tenured to Retired, the state of the Professor Clark object will change.
20
An Object Has Behavior Behavior determines how an object acts and reacts. The visible behavior of an object is modeled by the set of messages it can respond to (operations the object can perform). The second characteristic of an object is that it has behavior. Objects are intended to mirror the concepts that they are modeled after, including behavior. Behavior determines how an object acts and reacts to requests from other objects. Object behavior is represented by the operations that the object can perform. For example, Professor Clark can choose to take a sabbatical once every five years. The Professor Clark object represents this behavior through the TakeSabbatical() operation.
21
An Object Has Identity Each object has a unique identity, even if the state is identical to that of another object. In the real world, two people can share the same characteristics: name, birth date, job description. Yet, there is no doubt that they are two individuals with a unique identity. The same concept holds true for objects. Although two objects may share the same state (attributes and relationships), they are separate, independent objects with their own unique identity. Professor “J Clark” teaches Biology Professor “J Clark” teaches Biology
22
What Is a Class? A class is a description of a set of objects that share the same attributes, operations, relationships, and semantics. An object is an instance of a class. An abstraction in that it Emphasizes relevant characteristics. Suppresses other characteristics. A Class can be defined as: A description of a set of objects that share the same attributes, operations, relationships, and semantics. (The Unified Modeling Language User Guide, Booch, 1999) There are many objects identified for any domain. Recognizing the commonalties among the objects and defining classes helps us deal with the potential complexity. The OO principle abstraction helps us deal with complexity.
23
Cont.. class class_name { private data and functions public:
public data and functions } object_names; Where, class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class.
24
Access Specifiers Can be listed in any order in a class
Used to control access to members of the class public: can be accessed by functions outside of the class private: can only be called by or accessed by functions that are members of the class Can be listed in any order in a class Can appear multiple times in a class If not specified, the default is private
25
Using const With Member Functions
const appearing after the parentheses in a member function declaration specifies that the function will not change any data in the calling object. const vs. #define #define – C-style of naming constants: #define NUM_STATES 50 Note no semicolon at end Interpreted by pre-processor rather than compiler Does not occupy memory location like const
26
Defining a Member Function
When defining a member function: Put prototype in class declaration Define function using class name and scope resolution operator (::) int Rectangle::setWidth(double w) { width = w; }
27
Accessors and Mutators
Mutator: a member function that stores a value in a private member variable, or changes its value in some way Accessor: function that retrieves a value from a private member variable. Accessors do not change an object's data, so they should be marked const.
28
Defining an Instance of a Class
An object is an instance of a class Defined like structure variables: Rectangle r; Access members using dot operator: r.setWidth(5.2); cout << r.getWidth(); Compiler error if attempt to access private member using dot operator
29
Cont..
30
Avoiding Stale Data Some data is the result of a calculation.
In the Rectangle class the area of a rectangle is calculated. length x width If we were to use an area variable here in the Rectangle class, its value would be dependent on the length and the width. If we change length or width without updating area, then area would become stale. To avoid stale data, it is best to calculate the value of that data within a member function rather than store it in a variable.
31
Pointer to an Object Can define a pointer to an object:
Rectangle *rPtr; Can access public members via pointer: rPtr = &otherRectangle; rPtr->setLength(12.5); cout << rPtr->getLenght() << endl; We can also use a pointer to dynamically allocate an object.
32
Another Example
33
Separating Specification from Implementation
Place class declaration in a header file that serves as the class specification file. Name the file ClassName.h, for example, Rectangle.h Place member function definitions in ClassName.cpp, for example, Rectangle.cpp File should #include the class specification file Programs that use the class must #include the class specification file, and be compiled and linked with the member function definitions
34
Example #define SIZE 100 // This creates the class stack. class stack
{ int stck[SIZE]; int tos; public: void init(); void push(int i); int pop(); }; By default members are private In C++, class creates a new data type that may be used to create objects of that type. Therefore, an object is an instance of a class in just the same way that some other variable is an instance of the int data type, for example. Put differently, a class is a logical abstraction, while an object is real. (That is, an object exists inside the memory of the computer.) The prototype for a member function within a class definition serves as that function's prototype in general
35
Cont.. Creating object stack mystack; Code a function
void stack::push(int i) { if(tos==SIZE) { cout << "Stack is full.\n"; return; } stck[tos] = i; tos++; :: --Scope resolution operator
36
Cont.. When you refer to a member of a class from a piece of code that is not part of the class, you must always do so in conjunction with an object of that class. Stack stack1. stack2; Stack1.init();
37
Complete example #include <iostream> using namespace std;
void stack::init() { tos = 0; } void stack::push(int i) if(tos==SIZE) { cout << "Stack is full.\n"; return; stck[tos] = i; tos++; int stack::pop() if(tos==0) { cout << "Stack underflow.\n"; return 0; }tos--; reutrn stck[tos];} #include <iostream> using namespace std; #define SIZE 100 // This creates the class stack. class stack { int stck[SIZE]; int tos; public: void init(); void push(int i); int pop(); }; int main() { stack stack1, stack2; stack1.init(); stack2.init(); stack1.push(1); stack2.push(2); stack1.push(3); stack2.push(4); cout << stack1.pop() << " "; cout << stack2.pop() << " "; cout << stack2.pop() << "\n"; return 0; } Recall that the private members of an object are accessible only by functions that are members of that object. For example, a statement like stack1.tos = 0; // Error, tos is private. could not be in the main() function of the previous program because tos is private
38
Cont.. ? stack1.tos = 0;
39
Function Overloading Polymorphism- Two or more functions can share the same name as long as their parameter declarations are different. In this situation, the functions that share the same name are said to be overloaded, and the process is referred to as function overloading. #include <iostream> using namespace std; // abs is overloaded three ways int abs(int i); double abs(double d); long abs(long l); int abs(int i) { cout << "Using integer abs()\n"; return i<0 ? -i : i; } double abs(double d) cout << "Using double abs()\n"; return d<0.0 ? -d : d; long abs(long l) { cout << "Using long abs()\n"; return l<0 ? -l : l; } int main() { cout << abs(-10) << "\n"; cout << abs(-11.0) << "\n"; cout << abs(-9L) << "\n"; return 0;}
40
Operator Overloading >> “get from” right shift
<<“send to” left shift + “addition” concatenation
41
The exit() Function Terminates the execution of a program
Can be called from any function Can pass an int value to operating system to indicate status of program termination Usually used for abnormal termination of program Requires cstdlib header file Example: exit(0); The cstdlib header defines two constants that are commonly passed, to indicate success or failure: exit(EXIT_SUCCESS); exit(EXIT_FAILURE);
42
Default Arguments C++ allows us to call a function without specifying all its arguments. Function should assign a default value to such arguments. Default values are specified when the function is declared. float tax(float tax_rate = 6) Only trailing arguments can have default values. void abc(int a, int b = 10, int c); // invalid sales_tax = tax(); // calculate tax using tax_rate 6 (default) sales_tax = tax(10); // calculate tax using tax_rate 10
43
Inline Functions Each time a function is called, a significant overhead is generated: Arguments are pushed onto the stack Various registers are saved Restored when the function returns. Inline functions are not actually called; rather, their code is expanded in line at the point of each invocation. Compiler replaces the function call with the corresponding function code. General Syntax to write inline functions: inline function prototype { //function body }
44
Inline Functions example
inline int max( int a, int b) { return a > b ? a : b } int main() {cout << max(10,20);} Larger size due to duplicated code. Best to inline only very small functions. Like the register specifier, inline is actually just a request to compiler. The compiler can chose to ignore it. If a function can not be inlined, it will be called as a normal function.
45
Inline Functions inside and outside classes
By default functions defined in a class are considered inline . Class A{ public: void abc(){ cout << “I am Inlined”; }; } We can define a function outside the class definition and still make it inline by just using the qualifier inline. Class A{ public: void abc(); }; inline void A :: abc(){ cout << “I am Inlined”; }
46
Classes, Objects and Memory
When an object is created memory is reserved Each object has its own copy of public and private data members An object has access to only its data members and not to data members of other objects name 65522 M1 age 65524 Objects Member Variables Memory Location name 65518 M2 age 65520
47
Member Functions What about member functions?
Member functions are created and memory is allocated to them only once when a class is declared All objects of a class access the same memory location where member functions are stored Separate copies of member functions are not present in every object like member variables
48
Fun A() Fun B() Fun C() Fun D()
Object A Object B Variable 1 Variable 2 Variable 3 Variable 4 Variable 1 Variable 2 Variable 3 Variable 4 Fun A() Fun B() Fun C() Fun D() Object C Object D Variable 1 Variable 2 Variable 3 Variable 4 Variable 1 Variable 2 Variable 3 Variable 4 Data members and member function in Memory
49
Static Data Members Static Private Member Variable
When you precede a member variable's declaration with static, you are telling the compiler that only one copy of that variable will exist and that all objects of the class will share that variable. A static member variable exists before any object of its class is created. Static Private Member Variable Like functions it is possible to create common member variables using ‘static’ keyword Only one copy of that member is created for the whole class. Variable declared as static is initialized to 0 The static data variable is accessible within the class but it’s value remains in memory through out the whole program
50
Definition of static data member
When you declare a static data member within a class, you are not defining it. you must provide a global definition for it elsewhere, outside the class. This is done by redeclaring the static variable using the scope resolution operator Declaration of static variable inside class does not allocate storage class num { static int c; //static member variable declaration }; int num:: c=0; //static member variable definition
51
Static Public Member Variable
If a class public member variable is declared as static, it can be accessed directly from main Class name and scope operator is used to access the static public member variable No need to create object Same variable name can be used for global and local variable
52
Example : Static Public Member Variable
class test { public: static int c; //static public }; int test::c ==22; //definition outside int c =11; //global variable void main() { int c = //local variable cout << “ Class member c = “<<test::c; cout << “ Global member c = “<<::c; cout << “ Local Variable c = “<<c; } //no need to create objects to access static public member variable
53
Static Public Member Function
Functions can also be declared static Static member functions can be invoked directly with a class name Can access only static members of the class Static member functions can also be invoked using objects To "preinitialize" private static data before any object is actually created. class demo { private static int c; public: static void display() cout <<c; } }; int demo::c=3; Static member variable declaration void main() { demo::display(); } Static member Function declaration Can be accessed without creating objects
54
Static Private Member Function
In this case the private member function can only be invoked using a static public member function Also the same rule i.e it can access only the static members of the class is applicable here
55
Static Object Object is a composition of one or more member variables
Objects can be declared as ‘static’ in main Declaring Object as Static initializes all class data members variables to 0 It does not make the entire class static including member function
56
Example : Static Objects
class test { private: int c; int k; public: void plus() c=c+2; k= k+2 } void show() cout <<“c = “<< c <<endl; cout<<“k =“<< k << endl; }; void main() { static test t1; //static object t1. plus(); t1.show(); } Note : Try running the same program by removing the static keyword above
57
Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class.
58
Example When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically. add a ; Not only creates the object a of type add but also initializes its data members m and n to zero. class add { int m, n ; public : add (void) ; ------ }; add :: add (void) m = 0; n = 0; }
59
Cont.. There is no need to write any statement to invoke the constructor function. If a ‘normal’ member function is defined for zero initialization, we would need to invoke this function for each of the objects separately. A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A : : A ( )
60
Characteristics of Constructors
They should be declared in the public section. They are invoked automatically when the objects are created. They do not have return types, not even void and they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Like other C++ functions, Constructors can have default arguments. Constructors can not be virtual.
61
Characteristics of Constructors
They make ‘implicit calls’ to the operators new and delete when memory allocation is required. When a constructor is declared for a class initialization of the class objects becomes mandatory.
62
Parameterized Constructors
It may be necessary to initialize the various data elements of different objects with different values when they are created. This is achieved by passing arguments to the constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors.
63
Example class Crectangle { int width, height; public: CRectangle (int,int); int area () {return (width*height);} }; CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared. Two ways Calling: Explicit add sum = add(2,3); Implicit add sum(2,3) Shorthand method
64
Overloading constructors
Like any other function, a constructor can also be overloaded with more than one function that have the same name but different types or number of parameters. For overloaded functions the compiler will call the one whose parameters match the arguments used in the function call. (same as in function overloading) In the case of constructors, which are automatically called when an object is created, the one executed is the one that matches the arguments passed on the object declaration.
65
Example
66
NOTE if we declare a new object and we want to use its default constructor (the one without parameters), we do not include parentheses (): CRectangle rectb; // right CRectangle rectb(); // wrong!
67
Default Constructor If you do not declare any constructors in a class definition, the compiler assumes the class to have a default constructor with no arguments. But as soon as you declare your own constructor for a class, the compiler no longer provides an implicit default constructor. So you have to declare all objects of that class according to the constructor prototypes you defined for the class.
68
Cont.. class Cexample { public: int a,b,c;
CExample (int n, int m) { a=n; b=m; }; void multiply () { c=a*b; }; }; Here we have declared a constructor that takes two parameters of type int. Therefore the following object declaration would be correct: CExample ex (2,3);
69
Cont.. But, CExample ex; Would not be correct, since we have declared the class to have an explicit constructor, thus replacing the default constructor.
70
Destructors Member function automatically called when an object is destroyed Destructor name is ~classname(), e.g., ~Rectangle() Has no return type; takes no arguments Only one destructor per class, i.e., it cannot be overloaded If constructor allocates dynamic memory, destructor should release it
71
Destructors It will be invoked implicitly by the compiler upon exit from the program (or block or function) to clean up storage that is no longer accessible. Whenever new is used to allocate memory in the constructors, we should use delete to free that memory. Objects are destroyed in the reverse order of creation.
72
Objects as Function Arguments
Objects can also be passed as function arguments just like any other data type Three ways by which arguments can be passed Pass by value: Actual object is copied and sent to function as a formal object. Pass by reference Pass by address
73
Objects Passing (by value)
Any changes made to the object inside the function do not affect the object used to call the function. Copy of the function is passed to the function. A new object comes into existence. When the function terminates, the copy of the argument is destroyed.
74
Objects Passing (by value)
Object’s constructor is called when the copy is made? Object’s destructor is called when the copy is destroyed? The normal constructor is not called to create copy. Copy constructor is called that defines how a copy of an object is made. The default copy constructor creates a bitwise(identical) copy of the object. Normal constructor is used to initialize the object, but you want to use the current state of the object at the time of argument passing.
75
Example : Object as a function argument – pass by value
class life { private: int mfgyr; int expyr; int yr; public: void getyrs(); cout <<“Enter MFG year:”; cin >>mfgyr; cout <<“Enter EXP year:”; cin >>expyr; } void period (life); //prototype }; void life:: period(life y1) //definition { yr = y1.expyr – y1.mfgyr; cout <<“Life of the product:”; cout <<yr<<“Years”; } void main () { life l1; l1.getyrs(); l1.period(l1) //passing object as arg }
76
Example : Object as a function argument – pass by address
class life { private: int mfgyr; int expyr; int yr; public: void getyrs(); cout <<“Enter MFG year:”; cin >>mfgyr; cout <<“Enter EXP year:”; cin >>expyr; } void period (life *);//prototype }; void life:: period(life *y1) //definition { yr = y1->expyr – y1->mfgyr; cout <<“Life of the product:”; cout <<yr<<“Years”; } void main () { life l1; l1.getyrs(); l1.period(&l1) //passing object as arg }
77
Example : Object as a function argument – pass by Reference
class life { private: int mfgyr; int expyr; int yr; public: void getyrs(); cout <<“Enter MFG year:”; cin >>mfgyr; cout <<“Enter EXP year:”; cin >>expyr; } void period (life &);//prototype }; void life:: period(life &y1) //definition { yr = y1.expyr – y1.mfgyr; cout <<“Life of the product:”; cout <<yr<<“Years”; } void main () { life l1; l1.getyrs(); l1.period(l1) //passing object as arg }
78
Returning Objects A function may return an object to the caller
To hold a return value a temporary object is automatically created. After the value has been return, this object is destroyed.
79
Example : Array of Objects
Arrays are collection of similar data types Classes are also user defined data type, hence objects of the same class can be a collection of similar data types Array of objects can be created Array elements are stored in continuous memory locations Example : Array of Objects class player { private: char name [50]; int age; public: void input (); void display(); }; void main() { player tennis; player cricket[3]; player football[4]; }
80
Contd.. Array of objects of type ‘player’ is created
cricket[3] Array of objects of type ‘player’ is created cricket[3] – is an array named ‘cricket’ containing objects of type player Array contains ‘name’ and ‘age’ information for 3 objects name cricket[0] age name cricket[1] age name cricket[2] age
81
Example : Sample Program for Array of Objects
class player { private: char name [50]; int age; public: void input (); void display(); }; void player:: display() { cout <<“Player Name:”<< name; cout <<“Player Age:” <<age; } void main () { player cricket[3]; cout <<“Enter name and age”; for (int i = 0; i<3; i++) cricket[i].input(); for (int j = 0; j<3; j++) cricket[j] .display(); } void player :: input() { cout <<“Enter Name:”; cin >>name; cout <<“Enter Age:”; cin >>age; }
82
Example2 : Sample Program for Array of Objects
class example { int data; public: void set_data(int x) data = x; } int get_data() return data; }; void main () { example obj[3]; for (int i = 0; i<3; i++) obj[i].set_data(); for (int j = 0; j<3; j++) cout<<obj[j] .get_data(); }
83
Initialization of array with constructor
If a class defines a parameterized constructor, you have to initialize each element of array. Case 1: if constructor has only one parameter obj[3] = {10,20,30}; Case2: if constructor requires two or more arguments Obj[3] = {example(2,3),example(10,20),example(30,40)};
84
CASE1 : Sample Program for Array of Objects initialization
class example { int data; public: void set_data(int x) data = x; } int get_data() return data; }; void main () { example obj[3]; for (int i = 0; i<3; i++) obj[i].set_data(); for (int j = 0; j<3; j++) cout<<obj[j] .get_data(); } example(int d) { data = d; } void set_data(int x) data = x; int get_data() return data; }; example obj[3] = {10,20,30};
85
CASE2 : Sample Program for Array of Objects initialization
class example { int data; public: example(int d) data = d; } int get_data() return data; }; int data1; int data2; void main () { example obj[3] = {10,20,30}; for (int j = 0; j<3; j++) cout<<obj[j] .get_data(); } example obj[3] = {exmple(10,20), example(20,30),example(30,40)}; example(int d1,int d2) { data1 = d1; data2 = d2; } for (int j = 0; j<3; j++) { cout<<obj[j].get_data1(); cout<<obj[j].get_data2() } int get_data1() { return data1; } int get_data2() return data2;
86
const Pointers #include<iostream.h> void main() { int x=10,y=20; int *a=&x; const int *b=&x; int *const c=&x; const int *const d=&x; a=&y; //valid b=&y; //valid c=&y; //Invalid d=&y; //Invalid *a=*a+10; //valid *b=*b+10; //Invalid *c=*c+10; //valid *d=*d+10; //Invalid } Can make a pointer as constant. Cannot change the value of pointer. <type> *const <variable name> Modification in Pointer Modification in value
87
const Pointers char *p = “Hello”; *p = ‘M’; p = “Bye”; const char *p = “Hello”; char *const p = “Hello”; const char *const p=“Hello”; //Pointer is variable, so is string //works //String is fixed, Pointer is not //error //works //Pointer is fixed string is not //works //error //String is fixed, so is pointer //error
88
const Member Function The member function of a class can be declared with ‘const’ keyword Constant function cannot modify any data in the class class A { int c; public: void add(int a, int b) const c= a+b //invalid cout<<a; //valid cout <<b; //valid }
89
const Objects Objects can also be declared constant using const keyword before object declaration. const example(20); A constant object can call only const member functions.
90
Pointers to Objects class cl { int i; public: cl(int j) { i=j; } int get_i() { return i; } }; void main() { cl ob(88), *p; p = &ob; // get address of ob cout << p->get_i(); // use -> operator }
91
The this Pointer A pointer to the invoking object (that is, the object on which the function is called). It is automatically passed as an implicit argument at the time of member function calling. this pointer is automatically passed to all member functions Static member functions do not have a this pointer. this pointer is not passed to friend functions. Member function can access the data members directly or using this pointer
92
The this Pointer class pwr { double b; int e; double val; public: pwr(double base, int exp); double get_pwr() { return val; } }; pwr::pwr(double base, int exp) { this->b = base; this->e = exp; this->val = 1; for( ; exp>0; exp--) this->val = this->val * this->b; } pwr::pwr(double base, int exp) { b = base; e = exp; val = 1; for( ; exp>0; exp--) val = val * b; }
93
Pointers to Class Members
C++ allows you to generate a special type of pointer that "points" generically to a member of a class, not to a specific instance of that member in an object. ::* , .* , ->* operators are used to create a pointer to class members and access the class members. 1. pointer to data member: <type> classname ::*<pointer name> 2. pointer to member function: <ret-type>(classname::*<pointer name>)(<parameter List>)
94
Pointers to Class Members
class cl { public: cl(int i) val=i; } int val; int double_val() return val+val; }; int main() { int cl::*data; // data member pointer int(cl::*func)();// function member pointer cl ob1(1), ob2(2); // create objects cl *p1; p1 = &ob1; // access objects through a pointer data = &cl::val; // get offset of val func = &cl::double_val; // get offset of double_val() cout << p1->*data << " “<< ob2.*data; cout << "Here they are doubled: "; cout << (p1->*func)() << " "; cout << (ob2.*func)() << "\n"; return 0; }
95
Object Assignment You can assign one object to another object. class example { int i; Public: void set_i(int n){ i=n;} int get_i() {return i;} }; void main() { example ob1, ob2; Ob1.set_i(99); Ob2 =ob1; cout << “This is ob2’s i: “<< ob2.get_i(); getch(); } By default , all data from one object is assigned to the other by use of a bit- by-bit copy
96
Copy Constructor Used to declare and initialize an object from another object. example e2(e1); Default copy constructor copies field-to-field Default copy constructor works fine in many cases Explicit Use: Building a(4); // standard constructor call Building b(a); // b is now a deep copy of a Implicit Use #1: Building b = a;// implicit call to the copy constructor Implicit Use #2: When an object is returned by value from a function When a copy of an object is made to be passed to a function
97
Copy Constructor Example
98
Copy Constructor Problem: what if object contains a pointer?
class SomeClass { int *value; public: SomeClass(int val = 0) { *value = val; } int getVal(); void setVal(int); };
99
Copy Constructor What we get using member-wise copy with objects containing dynamic memory: SomeClass object1(5); SomeClass object2 = object1; object2.setVal(13); cout << object1.getVal(); // also 13
100
Programmer-Defined Copy Constructor
Allows us to solve problem with objects containing pointers: SomeClass::SomeClass(const SomeClass &obj) { value = new int; *value = *(obj.value); } Copy constructor takes a reference parameter to an object of the class
101
Programmer-Defined Copy Constructor
Each object now points to separate dynamic memory: SomeClass object1(5); SomeClass object2 = object1; object2.setVal(13); cout << object1.getVal(); //5
102
Example
103
Constructors / Destructors Revisited
The compiler implicitly calls the constructor and destructor Explicit calls to a constructor and destructor is also allowed Calling methods are different for both The constructor and destructor can call each other The constructor can be called without the object and class The destructor needs to be called with the help of object and class
104
ex. example : : ~example();
Contd.. class example { }; class named example example() { } constructor definition destructor definition ~example() { } example ex; creation object named ex example(); explicit constructor call ex. example : : ~example(); explicit destructor call
105
Explicit Constructor and Destructor call
class text { public: text( ) //constructor cout<<“Constructor call”<<endl; } ~text( ) //destructor cout <<“Destructor call”<<endl; }; void main() { text t; text(); t.text::~text(); }
106
Qualifier and Nested Class
Class can also be nested i.e declaration can be done inside the class The outer class is called as a qualifier The class defined inside – nested class Helps to construct more powerful data structure
107
Contd.. class A int x Qualifier or Host class
class B To create an object of A: A a; int y; To create an object of B: A :: B b; Nested class
108
Example: Qualifier and Nested Class
class A { public: int x; A() { x =10; } class B int y; B() { y =20; } void show() A a; cout <<“x = “ <<a.x <<endl; cout <<“y=“<<y<<endl; } }; void main() { A :: B b; b.show(); } Output x = 10 Y = 20
109
Anonymous Objects Objects can be created without names – anonymous objects Calling constructors directly from main creates anonymous objects Other member functions cannot be called directly Anonymous object cannot be implemented without the use of constructor and destructor
110
Example: Anonymous object
class Any { private: int x; public: Any() cout <<“first constructor”<< endl; } Any (int n) cout <<“second constructor”<<endl; x=n; cout <<“The value of x = “<<x; }; int main() { Any(); Any(55); return 0; } Output first constructor second constructor The value of x = 55
111
Private Constructors Constructors declared in the private block
Cannot be invoked implicitly Must be invoked explicitly Private constructors with simple object is not possible Private constructor - works with pointer object Constructor has to be called from a public function
112
Example: Private constructor
class pcon{ private: int x; pcon(){ cout <<"First constructor"<< endl; } pcon(int n){ cout <<"constructor invoked"<<endl; x=n; cout <<"The value of x = "<<x; public: void callconstr(){ pcon(55); }; void main(){ pcon *a; a->callconstr();
113
Other Properties The constructor can also be named as main() for a class named ‘main’. Like other functions, constructors also support recursion.
114
Global objects Declaration of objects is allowed before main()
Declaration of objects invoke constructors and constructors can call any member function Object declared before main() is called as global object For global objects constructor is executed before main() and destructor after main()
115
Example: Global object
class A { private: int x; public: A(){ cout <<“The constructor is called”<<endl; x =15; show( ); } void show(){ cout <<“The value of x = “<<x; }; A a1; void main(){ cout <<“I am in main()”;
116
Questions- Error & Output
#include<iostream> using namespace std; class Test { int value; public: Test(int v = 0) {value = v;} int getValue() const {return value;} }; int main() { Test t(20); cout<<t.getValue(); return 0; } #include<iostream> using namespace std; class Test { int value; public: Test(int v = 0) {value = v;} int getValue() {return value;} }; int main() { const Test t; cout<<t.getValue(); return 0; } #include<iostream> using namespace std; class Test { int value; public: Test(int v = 0) {value = v;} int Value(int x = 0) const { value = x; return value; } }; int main() { Test t(20); cout<<t.Value(); return 0;
117
Questions- Error & Output
#include<iostream> using namespace std; class Test { int &t; public: Test(int &t):t(t) {} //Initializer list must be used here as well int getT() {return t;} }; int main() { int x = 20; Test t1(x); cout<<t1.getT()<<endl; x = 30; cout<<t1.getT()<<endl; getchar(); return 0; } #include<iostream> using namespace std; class Test { const int t; public: Test(int t):t(t) {} //Initializer list must be used int getT() {return t;} }; int main() Test t1(10); cout<<t1.getT(); return 0; }
118
Questions- Error & Output
/* local variable is same as a member's name */ class Test { Private: int x; Public: void setX (int x) { // The 'this' pointer is used to retrieve the object's x // hidden by the local variable 'x' this->x = x; } void print() { cout << "x = " << x << endl; } }; int main() Test obj; int x = 20; obj.setX(x); obj.print(); return 0; } class Test { Private: int x; int y; public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test &setX(int a) { x = a; return *this; } Test &setY(int b) { y = b; return *this; } void print() { cout << "x = " << x << " y = " << y; } }; int main() { Test obj1(5, 5); // Chained function calls. All calls modify the same object // as the same object is returned by reference obj1.setX(10).setY(20); obj1.print(); return 0;}
119
#include <iostream>
using namespace std; class Box { public: // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) cout <<"Constructor called." << endl; Length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } int compare(Box box) { return this->Volume() > box.Volume(); } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 if(Box1.compare(Box2)) cout << "Box2 is smaller than Box1" <<endl; } else cout << "Box2 is equal to or larger than Box1" <<endl; return 0;
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.