0% found this document useful (0 votes)
1 views24 pages

11-oo-objects plc

The document discusses Object Oriented Programming (OOP) concepts including abstraction, encapsulation, inheritance, and the implementation of objects in C++. It covers key topics such as constructors, destructors, copy constructors, the const keyword, operator overloading, and the use of friends in classes. The document provides examples and explanations of how these concepts are applied in C++ programming.
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)
1 views24 pages

11-oo-objects plc

The document discusses Object Oriented Programming (OOP) concepts including abstraction, encapsulation, inheritance, and the implementation of objects in C++. It covers key topics such as constructors, destructors, copy constructors, the const keyword, operator overloading, and the use of friends in classes. The document provides examples and explanations of how these concepts are applied in C++ programming.
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/ 24

Programming Languages:OO Paradigm, Objects

Programming Languages:
OO Paradigm, Objects

Onur Tolga Şehitoğlu

Computer Engineering,METU

15 April 2008
Programming Languages:OO Paradigm, Objects

Outline

1 Object Oriented Programming Copy Constructor


2 Constructors/Destructors 3 const Keyword
Constructors 4 Operator Overloading
Heap Objects Friends
Destructors 5 Implementation of Objects
Programming Languages:OO Paradigm, Objects
Object Oriented Programming

Object Oriented Programming

Abstraction
Encapsulation
Hiding
Inheritance
Programming Languages:OO Paradigm, Objects
Object Oriented Programming

Encapsulation/Scope

Person
Objects consist of: name
attributes (member variables) surname
methods (member functions) no
encapsulated in a package scope getname()
setno()
attributes: state of objects
methods: behaviour of objects
alternative terminalogy: messages
call a method ≡ send message to an object
A class is the family for similar objects.
An object is an instance of a class.
Programming Languages:OO Paradigm, Objects
Object Oriented Programming

class P e r s o n {
char name [40] , surname [40];
int no ;
public :
const char * getname () { return name ;}
void s e t n o ( int );
} obj ;

void P e r s o n :: s e t n o ( int a ) {
no = a ;
}

C++ allows definitions inside the class or outside by scope


operator ‘::’
Environment is recursive collateral.
obj.getname(); calls the method in the context of object obj.
keyword denotes pointer to current object in member
this
functions. ( self () in some other languages)
Programming Languages:OO Paradigm, Objects
Object Oriented Programming

Hiding

Interface vs detail. Details are hidden, only interface members


are exported outside.
C++ uses private :, protected:, and public : labels to mark hiding.
only members following a public : label are visible outside (the
object for example). Member functions can access all
members regardless of their labels.
obj.setno(4) is legal, obj.no is not.
Hiding depends on scope and it is lexical. In C++ pointer
conversions can violate hiding.
By convention all member variables should be private, some
member functions can be private, only some of member
functions are public.
protected keyword is useful with inheritance.
Programming Languages:OO Paradigm, Objects
Object Oriented Programming

Abstraction

An object is an abstraction over the programming entity


defined by the model in the design.
Model: customer, bank, registration, course, advisor, mail,
chatroom,...
Class should provide:
Transparent behaviour for the objects, access via interface
functions.
Data integrity. Objects should be valid through their lifetimes.
Data integrity at the beginning of lifetime provided by
constructors (+destructors in C++)
Programming Languages:OO Paradigm, Objects
Constructors/Destructors
Constructors

Constructors

Special member functions called when lifetime of the object


starts just after storage of members are ready
Automatically called. No explicit calls.
no return value, name is same with the class
can be overloaded
class P e r s o n {
char *name [40] , * surname [40];
int no ;
public :
P e r s o n ( const char *n , const char * s ) {
s t r c p y (name ,n) ; s t r c p y ( surname , s ) ; no =0;
}
P e r s o n () { name [0]=0; surname [0]=0; no =0;}
} obj ;
Programming Languages:OO Paradigm, Objects
Constructors/Destructors
Constructors

Constructors can be overloaded


Definition Constructor
Person a ; Person()
Person a("ali","veli"); Person(const char *, const char *)
Number a=3; Number(int)
Number a(3); Number(int)
Number b=a; Number(Number &a)
Number a[2]={0,1} Number(int)
If no constructor implemented, empty constructor (do
nothing) assumed
If at least one constructor exists, variables should match at
least one of them, no empty constructor assumed
Constructors are called by the language when lifetime started:
1 start of program for global objects
2 entrance to function for local objects
3 when heap objects are created (with new)
Programming Languages:OO Paradigm, Objects
Constructors/Destructors
Heap Objects

Heap Objects

new and delete operators instead of malloc() and free().


Why?
Person *p=new Person("ali","veli");
delete p;

Array allocation/deallocation:
Person *p=new Person[100];
delete [] p;
Programming Languages:OO Paradigm, Objects
Constructors/Destructors
Destructors

Destructors

When storage (members) of an object allocated dynamically


Lifetime is over : garbage
We need calls to collect heap variables within the object
Java solution: garbage collector does the job. We need
nothing
C++: destructors: member functions called when lifetime is
over.
A class only have one destructor with exact type and name:
~ClassName(). Called:
1 end of program for global objects
2 return from function for local objects
3 when heap objects are deallocated (with delete )
Programming Languages:OO Paradigm, Objects
Constructors/Destructors
Copy Constructor

Destructor does not solve all problems with objects with heap
members:
Semantics of assignment
Semantics of parameter passing
Semantics of return value
Initialization
Default behaviour of C++ is copy member values byte by
byte.
Java assigns/passes by reference. No copying.
C++ Solution: implement your own semantic by Copy
constructor and overloading assignment operator.
Assignment operator destroys an existing object and replaces
with the data from new one, copy constructor copies data into
an empty object.
Programming Languages:OO Paradigm, Objects
Constructors/Destructors
Copy Constructor

Copy Constructor

Type is: ClassName(const ClassName &)


Called when:
Object passed by value: void add(ClassName a) {...}
Object initialized by object: ClassName a,b=a;
Object returned as a value ClassName getVal() {...}
Last one is a little tricky.
Default behaviour exists even if it other constructors exist.
Programming Languages:OO Paradigm, Objects
Constructors/Destructors
Copy Constructor

class L i s t {
struct Node { int x ; Node * n e x t } * head ;
public : L i s t () { head =NULL;}
L i s t ( c o n s L i s t &); // Copy c o n s t r u c t o r
~ L i s t ();
};
void p a s s b y v a l u e ( L i s t a) {
...

Copy Constructor
}
L i s t r e t u r n a s v a l u e ( L i s t &a) {
L i s t b=a; Copy Constructor, explicit
...
return a;
}
...Copy Constructor
p a s s b y v a l u e (c);
...
d= r e t u r n a s v a l u e ( c );
...
Programming Languages:OO Paradigm, Objects
Constructors/Destructors
Copy Constructor

Pass by value of objects are constructed by the copy


constructor
Return an object as a value creates a temporary object in
place of return and uses it:
d= returnasvalue (c); ≡ { List tmp=returnasvalue(c); d=tmp; }

Temporary objects are created at such expressions and


deallocated at the end of the line (at ‘;’), destructors are
called regularly.
Explicit call to a constructor also creates such a temporary
object.
g=Person("ali","veli");

C++ optimizer avoids copy constructor calls when possible.


List f() { List t;...; return t;} ... ; d=f(); ...
Programming Languages:OO Paradigm, Objects
const Keyword

const Keyword

C++ does strict type checking on constant restriction on const

const char *p vs char *const q

1 p[3]=’a’; ×

2 q[3]=’a’;

3 p++;
4 q++; ×
const char * const p

f(const ClassName &a) makes the parameter object constant


during the function scope
makes the returned object reference
const ClassName &f()
constant in expression containing the function call
What’s beside assignment? constant member functions
Programming Languages:OO Paradigm, Objects
const Keyword

Constant Member Functions

void f(const Rational &a) { ...; a.clear(3);...;a.out();}


void Rational::clear() { a=b=0;}
What is wrong above?
void Rational::out() const {...; a=b=0; }
const keyword preceding the function body makes member
function a constant function.
Constant functions cannot update member variables, only can
inspect them
a=b=0 in out() is invalid above
If an object is constant, only constant member functions can
be called.
a.clear(3); is invalid above
Type system of C++ prohibits those → Syntax error.
Programming Languages:OO Paradigm, Objects
Operator Overloading

Operator Overloading

Not an essential feature of object oriented programming but


improves readability in some cases.
Especially usefull in implementing selector abstraction, algebra
based applications.
Do not use it when the operator is not intuitive for the
context (class and the operation).
C++ allows overloading of existing operators with same arity
and precedence and only if at least one class type involves in
the operator
Operator can be implemented as a member function (first
parameter is the class) or as an external function (which has
at least one parameter being a class)
Programming Languages:OO Paradigm, Objects
Operator Overloading

All C++ operators except ‘.’ , ‘?:’, ‘::’, ‘.*’ and ‘->*’
For unary operators:
1 void ClassName::operator++();
2 void operator++(ClassName &a);
For binary operators:
1 void ClassName::operator&&(int a);
2 void operator&&(int a,ClassName &b);
First versions are member functions, can exist private
members. Only operand in unary case, LHS in binary case is
the current object
Second versions are outside of the definition. You need friend
declaration if they need to access private members.
Programming Languages:OO Paradigm, Objects
Operator Overloading

Rational & R a t i o n a l :: operator +( R a t i o n a l &b) {...}


Rational & R a t i o n a l :: operator +( int n) {...}
Rational & R a t i o n a l :: operator <( R a t i o n a l &b) {...}
Rational & R a t i o n a l :: operator !() {...}
Rational & R a t i o n a l :: operator ++() {...}
Rational & R a t i o n a l :: operator ++( int n o u s e ) {...}
Rational & R a t i o n a l :: operator double () {...}

void Hash :: operator =( Hash & a ) {...}


double Hash :: operator []( int a ) {...}
double Hash :: operator []( const char a []) {...}
Hash & Hash :: operator ()( const char a []) {...}

double P o i n t e r :: operator *() {...}


void * P o i n t e r :: new ( s i z e t s i z e ) {...}
void * P o i n t e r :: delete ( void *p , s i z e t s i z e ) {...}

R a t i o n a l a ,b , c ; Hash h , j ; P o i n t e r p ,* q;
a +b; a +3; if (a <b) ... ; !a;
++ a ; a ++; x =( double ) a ;

h= j ; x =h [3]; x =h[ " ali " ]; i =h( "a - b " );

x =* p; q= new P o i n t e r ; delete q;
Programming Languages:OO Paradigm, Objects
Operator Overloading

int operator +( int a , R a t i o n a l &b) {...}


R a t i o n a l & operator ++( R a t i o n a l &b) {...}
o s t r e a m & operator < <( o s t r e a m & os , R a t i o n a l & a ) {...}
i s t r e a m & operator > >( i s t r e a m & os , R a t i o n a l & a ) {...}

void operator +=( Hash &a , R a t i o n a l b) {...}

R a t i o n a l a ,b; Hash h , j ;

i = i +a;
++ a ;
c o u t << a ; c o u t << 3 << a << b ;
c i n >> b;
h += a ;
Programming Languages:OO Paradigm, Objects
Operator Overloading
Friends

Friends

When an external function or class needs to ac-


cess private members, friend declaration is used to grant access.
class R a t i o n a l {
friend class Hash ;
friend o s t r e a m & operator < <( o s t r e a m & , const R a t i o n a l &);
int a ,b;
public : ...
};
class Hash {
...
void operator +=( R a t i o n a l & a ) { .. a.a; .. a.b; ...}
};
o s t r e a m & operator < <( o s t r e a m & os , const R a t i o n a l & a ) {
o s << a.a << " // " << a.b << ’\ n ’;
return o s ;
}
Programming Languages:OO Paradigm, Objects
Implementation of Objects

Implementation of Objects

class Person
char name[40] 40*sizeof(char)
int id sizeof(int)
char * getname() sizeof(char *(*)())
void print() sizeof(void (*)())

What is size of object? Size of member variables + sizeof


member function pointers?
No! Each object does not have to store the function
information.
Its storage is same with the structure without any member
functions.
Function membership handled by the type system:
Person::getname() instead of getname()
Programming Languages:OO Paradigm, Objects
Implementation of Objects

How functions get object context (which object they refer


to?)?
Person::getname(Person *this) instead of no parameters
Person a; a.getname();
converted to Person::getname(&a); internally
All member references inside member function are converted
to:
char *getname() {.. id=5; ... ; strlen(name);...} →
char *Person::getname(Person *this) {
.. this->id=5; ... ; strlen(this->name);...}

You might also like