Object Oriented Programming: Lecture 7: Classes and Objects

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Object oriented Programming

Lecture 7: Classes and objects

Object oriented programming in C++ by Robert Lafore 1


Recap..
• Passing objects as arguments
• Returning objects

Object oriented programming in C++ by Robert Lafore 2


Recommended reads
Object oriented programming in C++ by Robert Lafore: Chapter 6

Object oriented programming in C++ by Robert Lafore 3


Objects are self-contained entities

• Each object has its own separate data items, so there must be a separate instance
of each data item for each object.
• However, the member functions are created and placed in memory only once!

Object oriented programming in C++ by Robert Lafore 4


Static Class Data
• If a data item in a class is declared as static, only one such item is created for the
entire class, no matter how many objects there are.
• A static data item is useful when all objects of the same class must share a
common item of information.
• While a normal static variable is used to retain information between calls to a
function, static class member data is used to share information among the
objects of a class.
• In a road-racing game, for example, a race car might want to know how many
other cars are still in the race.

Object oriented programming in C++ by Robert Lafore 5


• Static member data requires two separate statements:
• The variable’s declaration appears in the class definition,
• but the variable is actually defined outside the class, in much the same
way as a global variable.

int RaceCars::count = 0;

• Putting the definition of static member data outside the class also serves
to emphasize that the memory space for such data is allocated only once

Object oriented programming in C++ by Robert Lafore 6


class RaceCars int main()
{
{
private: RaceCar c1,c2;
static int num_of_cars; //only one data item for all objects cout << c1.get_count()<<endl;
cout << c2.get_count()<<endl;
int score;
public: RaceCar c3;
cout << c1.get_count() << endl;
RaceCar() {num_of_cars ++; } cout << c2.get_count() << endl;
int getcount(){ return num_of_cars; }
return 0;
int getScore(){ return score; } }
void setcount(int s){score=s; }
};
int RaceCars:: num_of_cars = 0;

Object oriented programming in C++ by Robert Lafore 7


• In C++, a static field can be accessed with an object and also without one. (Fields
that are not static are instance fields and always need a declared object when you
use them.)
int main()
{
RaceCar c1,c2;
cout << RaceCar:: num_of_cars;
cout << c1.get_count()<<endl;
}
• A static function is one you can use with or without a declared object. On the
other hand, a non-static function requires an object.
• When an object uses a non-static function, the function receives a pointer to the
object. The pointer is known as the this pointer

Object oriented programming in C++ by Robert Lafore 8


Note:
• Non-static functions can access static variables (provided there is an object) as
well as non-static ones.
• Static functions can access only static members; they cannot access non-static
variables (a field that is not associated with an object can be accessed only by a
function that is not associated with an object)

Object oriented programming in C++ by Robert Lafore 9


const Member Functions
• A const member function guarantees that it will never modify any of its class’s
member data.
class aClass
{
private:
int alpha;
public:
void nonFunc() //non-const member function
{ alpha = 99; } //OK
void conFunc() const //const member function
{ alpha = 99; } //ERROR: can’t modify a member
};

Object oriented programming in C++ by Robert Lafore 10


Member functions that do nothing but acquire data from an object are
obvious candidates for being made const

void showdist() const //display distance


{
cout << feet << “\’-” << inches << ‘\”’;
}

Object oriented programming in C++ by Robert Lafore 11


const Member Function Arguments
Distance Distance::add_dist(const Distance& d2) const
{
Distance temp; //temporary variable

// feet = 0; //ERROR: can’t modify this


// d2.feet = 0; //ERROR: can’t modify d2 dist3 = dist1.add_dist(dist2);

temp.inches = inches + d2.inches; //add the inches


temp.feet += feet + d2.feet; //add the feet
return temp;
}

Object oriented programming in C++ by Robert Lafore 12


const Objects
• When an object is declared as const, you can’t modify it.
• It follows that you can use only const member functions with it, because they’re
the only ones that guarantee not to modify it.

void showdist() const //display distance; const func int main()


{ cout << feet << “\’-” << inches << ‘\”’; } {
const Distance football(300, 0);
void getdist() //user input; non-const func // football.getdist(); //ERROR: getdist() not co
{ cout << “football = “;
cout << “\nEnter feet: “; cin >> feet; football.showdist(); //OK
cout << “Enter inches: “; cin >> inches; cout << endl;
} return 0;
}

Object oriented programming in C++ by Robert Lafore 13


Object oriented programming in C++ by Robert Lafore 14
Array of objects (Dynamic vs static array declaration)
int main() int main()
{ {
int size; Distance parr[2];
size = 4; for(int i = 0; i < 2; i++)
Distance* p; {
p = new Distance[size]; cin >> parr[i].feet;
For (int i=0;i<size;i++) }
{ return 0;
cin>>p[i].feet; }
cin >> p[i].inches;
}
return 0;
}

Object oriented programming in C++ by Robert Lafore 15


Chapter 7, Topic: array of objects
Object oriented programming in C++ by Robert Lafore

Object oriented programming in C++ by Robert Lafore 16


Object oriented programming in C++ by Robert Lafore 17
Pointer to objects
int main() int main()
{ {
Distance* distptr; //pointer to Distance Distance d;
distptr = new Distance; //points to new Distance object Distance* distptr; //pointer to Distance
distptr->getdist(); //access object members distptr = &d;
distptr->showdist(); // with -> operator distptr->getdist(); //access object members
cout << endl; distptr->showdist(); // with -> operator
return 0; cout << endl;
} return 0;
}

distptr.getdist(); // won’t work; distptr is not a variable..it is a pointer to a variable


The dot operator requires the identifier on its left to be a variable. Since distptr is a pointer to a
variable, we need another syntax. (->)

Chapter 10: pg 464, pointers to objects: Object oriented programming in C++ by Robert Lafore 18
Array of pointers (PF)
Collection of addresses

int main()
{
Int *arr_ptr [3];
Int x=0,y=1,z=3;
arr_ptr[0]=&x;
arr_ptr[1]=&y;
arr_ptr[2]=&z;

return 0;
}

Object oriented programming in C++ by Robert Lafore 19


RaceCar *c, *carr;
c = new RaceCar;
carr = new RaceCar[3];
//pointer to object
(*c).set_score(1);
//or
c->set_score(1);
cout<<"SCORE pointer: "<<c->get_score()<<endl;

//pointer to array of objects


carr->set_score(2);//set first index' values
carr++;
carr->set_score(4);
carr--;
cout << "SCORE array: " << carr[1].get_score() << endl;

Object oriented programming in C++ by Robert Lafore 20


Object oriented programming in C++ by Robert Lafore 21
Array of pointers to objects
Distance* DisPtr[100]; //array of pointers to distance
int n = 0; //number of distance objects in array
char choice;
do //put distance in array
{
DisPtr[n] = new Distance; //make new object
DisPtr[n]-> getdist();
n++;
cout << “Enter another (y/n)? “;
cin >> choice;
}
while( choice==’y’ );

Object oriented programming in C++ by Robert Lafore 22


this pointer
• points to the object itself
• any member function can find out the address of the object of which it is a
member
class where
{
private:
Int v;
public:
void reveal()
{ cout << “\nMy object’s address is “ << this;
//error:
cout << "äddress: *this " << (*this) << endl;}
};
Object oriented programming in C++ by Robert Lafore 23
Accessing Member Data with this
class what
{
private:
int alpha;
public:
void tester()
{
this->alpha = 11; //same as alpha = 11;
cout << this->alpha; //same as cout << alpha;
}
};

Object oriented programming in C++ by Robert Lafore 24


Using the this Pointer to Avoid Naming Collisions
void Time::setHour(int hour)
{
this->hour = hour;
//OR
( *this ).hour=hour;
}

See Dietal&dietal chapter 9: this pointer…

Object oriented programming in C++ by Robert Lafore 25


Using the this Pointer to Enable Cascaded Function Calls
• Cascading function calls: Invoking multiple functions in the same statement
• when multiple functions called using a single object name in a single statement, it
is known as cascaded function call in C++
#include<iostream>
using namespace std;
class Demo int main()
{ {
public: Demo FUN1() Demo ob;
{ cout <<"\nFUN1 CALLED"<<endl; return *this; }
public: Demo FUN2() ob.FUN1().FUN2().FUN3();
{ cout <<"\nFUN2 CALLED"<<endl; return *this; }
return 0;
public: Demo FUN3() }
{ cout <<"\nFUN3 CALLED"<<endl; return *this; }
};
Object oriented programming in C++ by Robert Lafore 26
int main()
int main()
{
{
void dispstr(char*); //prototype
char str1[] = “Defined as an array”;
char str[] = “Idle people have the least leisure.”;
char* str2 = “Defined as a pointer”;
dispstr(str); //display the string
cout << str1 << endl; // display both strings
return 0;
cout << str2 << endl;
}
// str1++; // can’t do this; str1 is a constant
//--------------------------------------------------------------
str2++; // this is OK, str2 is a pointer
void dispstr(char* ps)
cout << str2 << endl; // now str2 starts “efined...”
{
return 0;
while( *ps ) //until null character,
}
cout << *ps++; //print characters
cout << endl;
}

Object oriented programming in C++ by Robert Lafore 27


That’s it

Object oriented programming in C++ by Robert Lafore 28

You might also like