Vous êtes sur la page 1sur 6

So what is OOP ?

A program can be broken down into specific parts, and each of these parts can perform
fairly simple tasks. When all of these simple pieces are meshed together into a
program, it can produce a very complicated and useful application.

So what is an object ?
An object is a component of a program that knows how to perform certain actions and to
interact with other pieces of the program.

Or in a simple way “object is a user defined variable of type class”


// demonstrates a small, simple object
#include <iostream.h>
#include <conio.h>
class smallobj //define a class
{
private:
int somedata; //class data
public:
void setdata(int d) //member function to set data
{
somedata = d; int main()
} {
void showdata() clrscr();
//member function to display data smallobj s1, s2; //define two objects of class
{ smallobj
cout << "Data is " << somedata << endl; s1.setdata(1066); //call member function to
} set data
}; s2.setdata(1776);
s1.showdata(); //call member function to
display data
s2.showdata();
getch();
}
// objpart.cpp
#include<iostream.h>
#include<conio.h>
class part //define class
{
private:
int modelnumber; //ID number of widget
int partnumber; //ID number of widget part
float cost; //cost of part
public:
void setpart(int mn, int pn, float c) //set data
{
modelnumber = mn;
partnumber = pn; void main()
cost = c; {
} clrscr();
void showpart() //display data part part1; //define object
{ // of class part
cout << "Model " << modelnumber; part1.setpart(6244, 373, 217.55F); //call
cout << ", part " << partnumber; member function
cout << ", costs $" << cost << endl; part1.showpart(); //call member function
} getch();
}; }
Objects as function arguments
Call by value
Call by reference
Objects as function arguments
#include<iostream.h>
#include<conio.h>
class time
{
int hours, minutes;
public:
void gettime(int h, int m)
{ hours=h; minutes=m; } int main()
void puttime() {
clrscr();
{ cout<<hours<<"hours and "; time t1,t2,t3;
cout<<minutes<<"minutes"<<"\n"; } t1.gettime(2,45);
void sum(time, time);
}; t2.gettime(3,30);
void time :: sum(time t1, time t2) t3.sum(t1,t2);
{ cout<<"t1= "; t1.puttime();
minutes = t1.minutes + t2.minutes; cout<<"t2= "; t2.puttime();
hours = minutes/60; cout<<"t3= "; t3.puttime();
minutes = minutes%60; getch();
hours = hours + t1.hours + t2.hours; return 0;
} }
C++ Objects as Data Types

Vous aimerez peut-être aussi