SlideShare a Scribd company logo
1 of 30
Introduction to Classes The concept of a class
FOR MORE CLASSES VISIT
tutorialoutletdotcom
Introduction to Classes The concept of a class is the same as that of a
structure: it is a user-defined data type that is used to
create a group of variables that may have different data types. In
addition to the data members, a member of a class can also be a
function. A member function is in general specified in the class
definition by its function prototype with its
definition provided somewhere else in the program. You define a class
as follows:
class <class-name>
{
<Data-members-and/or-member functions-declarations>
}; A member of a class (data or function) can be public or private. In the
definition of a class, you use the label public to specify its public
members and the label private to specify its private members. Example
C1
class Demo1
{
public:
double getValue2(void);
void setValue2(double num);
double getAverage( );
double val1;
private:
double computeSum( );
double val2; // to return the value of the private data member
// to set the value of the private data member
// to compute the average of both values
// the public data member
// to compute the sum of both values
// the private data member }; ©2011 Gilbert Ndjatou Page 207
Definition of a Class Member Function When you write the definition of
a class member function, you must precede the name of the
function in the function header by the name of that class followed by the
scope resolution operator
( :: ). A class data member (public or private) can be accessed in the
body of a member function of that
class. A class member function (private or public) can be called in
another member function of that class. Example C2 Definitions of the
member functions of class Demo1: /*----------------------------------
function getValue2( ) --------------------------------------------------*/
/* returns the value of the private member variable
*/
double Demo1:: getValue2(void)
{
return (val2);
}
/*---------------------------------- function setValue2( )
--------------------------------------------------*/
/* set the value of the private member variable to the given value
*/
void Demo1:: setValue2(double num)
{
val2 = num;
}
/*---------------------------------- function getAverage( )
--------------------------------------------------*/
/* compute the average of both values and return it
*/
double Demo1:: getAverage(void)
{
double total;
total = computeSum( );
return(total / 2);
}
/*---------------------------------- function computeSum( )
------------------------------------------------*/
/* compute the sum of both values and return it
*/
double Demo1:: computeSum(void)
{
return (val1 + val2 ) ;
} ©2011 Gilbert Ndjatou Page 208 Declaration of a Class Variable (or
Object) A class variable is called object. You declare an object in the
same way that you declare a structure variable. As with structure
variables, when you declare an object, a member variable is created for
each data
member of the class. Example C3
Declaration Effects in Memory Demo1 item1; item1.val1
item1.val2 Demo1 item2; item2.val1
item2.val2 Specifying the Members of an Object You specify an object’s
public member variable in the same way that you specify a member of a
structure variable, by using the dot operator. You call a class public
member function on an object by preceding the function call with the
name of that object, followed by the dot operator. A private member
variable of an object can only be specified in a member function or a
friend
function of the class of that object. A private member function of a class
can be called on an object only in a member function or a
friend function of the class of that object. A class member function can
be called in a function that is not a class member function only on an
object. Example C4
Given the class Demo1 of example C1 and object item1 defined in
function main as follows:
Demo1 item1; ©2011 Gilbert Ndjatou Page 209 We have the following
access to the member functions and the member variable of object
item1:
Valid Access to the Members of Object item1
1. cin >> item1.val1;
2. item1.setValue2 (15);
3. cout << endl << “The average of:t”
4.
<< item1.val1 << “ and “
5.
<< item1.getValue2( ) << “ is: “
6.
<< item1.getAverage( ); Invalid Access to the Members of Object
item1
1. cin >> item1.val2;
2. item1.computeSum( );
3. getValue2( ); Effects
// read a value into the public member variable val1
// set the private member variable val2 to 15
// output the value of the member variable val1
// output the value of the member variable val2
// output the average of the values of both variables Reasons // val2 is a
private member variable
// computeSum is a private member function
/* in a function that is not a class member function, a class
member function must be called on an object */ Objects and the
Assignment Operator It is legal in C++ to assign an object to another
object of the same class. The assignment of an object to another
generates the member-wise assignments of the member
variables of both objects. Example C5
Given the class Demo1 of Example C1 and the following definitions of
objects:
The assignment: Demo1 item1, item2; item1 = item2; has the same
effect as:
item1.val1 = item2.val1;
item1.setValue2( item2.getValue2( ) ); Notes
1. The concept of combining a number of items such as variables and
functions into a package such as
an object is called encapsulation.
2. In a class definition, you can have any number of occurrences of the
labels public: and private: as
shown in the following example:
©2011 Gilbert Ndjatou Page 210 class SampleClass
{
Public:
void inputSomething( );
int stuff;
private:
int computeResult( int val);
int val1;
public:
int setvalue( );
int val2;
};
3. In a class definition, the section between the opening brace { and the
first access-specifier label,
public: or private: is a private section. For example, the following two
class definitions are
identical:
class SampleClass1
{
int computeResult( int val);
int val1;
public:
int setvalue( );
int val2;
}; class SampleClass2
{
private:
int computeResult( int val);
int val1;
public:
int setvalue( );
int val2;
}; 4. It is a common practice to specify the public members of a class
before the private members and to
list the member function prototypes before the member variables as we
have done with the definition
of the class Demo1 of Example C1. ©2011 Gilbert Ndjatou Page 211
Exercise C1*
Given the following class definition:
class Automobile
{
public:
void setPrice ( double newPrice );
void setProfit ( double newProfit );
double getPrice ( );
private:
double price;
double profit;
double getProfit ( );
}; // to set the value of price member variable
// to set the value of profit member variable
// to return the value of price member variable // to return the value of
profit member variable a. Write the definitions of the member functions
setPrice, setProfit, getPrice, and getProfit.
b. Given the following definitions of objects hyundai and jaguar in
function main:
Automobile hyunday, jaguar;
Which of the following statements are invalid? Also provide the reasons
why a statement is
invalid.
hyunday.price = 15000.00;
jaguar.setPrice( 45000.00 );
cout << jaguar.getProfit ( );
jaguar.setProfit( ); cout << jaguar.getPrice ( );
jaguar = hyunday;
setPrice ( 16500 );
c.
d.
e.
f. Write a statement to set the profit member variable of object jaguar to
3500.
Write a statement to read a price and set the price member variable of
object hyunday to it.
Write a statement to output the value of the price member variable of
object jaguar.
Is it possible to write a statement to output the value of the profit
member variable of objet
jaguar? Why?
g. Write the statements to do the following:
1. Assign the value of each member variable of object jaguar to the
corresponding member
variable of object hyunday, and then,
2. Change the value of the member variable price of object hyunday to
24000.00. ©2011 Gilbert Ndjatou Page 212 Exercise C2
Given the following class Automobile defined in exercise C1:
class Automobile
{
public:
void setPrice ( double newPrice );
void setProfit ( double newProfit );
double getPrice ( );
private:
double price;
double profit;
double getProfit ( );
}; // to set the value of price member variable
// to set the value of profit member variable
// to return the value of price member variable // to return the value of
profit member variable a. And given the following definitions of objects
sable and jeep in function main:
Automobile sable, jeep;
Which of the following statements are invalid? Also provide the reasons
why a statement is
invalid.
cin >> jeep.profit;
jeep.setPrice( 45000.00 );
cout << jeep.getProfit ( );
cout << jeep.getPrice ( );
sable.setProfit( );
jeep = sable;
cout << getPrice( );
b.
c.
d.
e. Write a statement to set the price member variable of object jeep to
22000.00.
Write a statement to read a profit and set the profit member variable of
object sable to it.
Write a statement to output the value of the price member variable of
object jeep.
Write the statements to assign the value of each member variable of
object jeep to the
corresponding member variable of object sable, and then to change the
value of member variable
profit of object sable to 4000.00. Exercise C3
Write the definition of function main that does the following:
a. Define an object of the class Demo1 (defined in example C1above)
b. Read two values and set the two member variables of this object to
those values.
c. Output the values of the member variables of this object with
appropriate messages.
d. Compute and print the average value of the member variables of this
object with an appropriate
message.
©2011 Gilbert Ndjatou Page 213 Classes and Functions A class can be
the return type of a function: a function can return an object. Example
C6
The following function reads the values for the two member variables of
an object of the type class
Demo1 (defined in example C1 above) and then returns that object.
Demo1 inputValues (void)
{
Demo1 temp;
double num;
cin >> temp.val1; // read a value for the first member variable of
the object /*--- read the second value and set the second member
variable of the object to it--------*/
cin >> num;
temp.setValue2(num);
return (temp);
}
/*----------------------------------- the above function is called as follows
---------------------------*/
Demo1 item;
item = inputValues( ); An object can be a value parameter of a function.
When a function with an object as value parameter is called, the value of
each member variable of
the object argument is copied to the corresponding member variable of
the object parameter. Example C7
The following function receives an object of the class Demo1 (defined in
example C1 above) as
argument, and returns five times the average of the values of its member
variables.
double average5 (Demo1 item )
{
double result;
result = 5 * item.getAverage( );
return result;
} ©2011 Gilbert Ndjatou Page 214 /*------------------------ the above
function may be called as follows ---------------------------*/
Demo1 stuff;
stuff.val1 = 10;
stuff.setValue2 ( 12 );
cout << endl << average5( stuff );
After this call of function average5( ), its body is executed as if it was
written as follows:
double average5 (Demo1 item )
{
item.val1 = stuff.val1;
item.setValue2( stuff.getValue2( ) );
double result;
result = 5 * item.getAverage( );
return result;
} An object can be a reference parameter of a function. When a function
with an object as a reference parameter is called, the object argument
replaces the
object parameter in the body of the function. Example C8
The following function receives an object of the class Demo1 (defined in
example C1 above) as
argument, and adds 3 to the value of each of its member variables.
void add3 (Demo1 &item)
{
int num;
item.val1 += 3;
num = item.getValue2( );
item.setValue2( num + 3 );
} /*----------------------------------- the above function is called as follows
---------------------------*/
Demo1 someItem;
someItem.val1 = 10;
someItem.setValue2 ( 15 );
add3( someItem );
// someItem.value1 = 13 and someItem.value2 = 18 ©2011 Gilbert
Ndjatou Page 215 After the above call of function add3( ), its body is
executed as if it was written as follows:
{
int num;
someItem.val1 += 3;
num = someItem.getValue2( );
someItem.setValue2( num + 3 );
} Exercise C4*
Using the definition of the class Demo1 given in example C1, do the
following:
a. Write a function addDemo1 that receives as arguments two objects of
the class Demo1 and then
builds and returns another object of the class Demo1 such that the value
of each of its member
variable of is the sum of the values of the corresponding member
variables of the objects received as
arguments.
b. Write a code segment to do the following:
i.
Declare objects obj1 and obj2 of the class Demo1.
ii.
Set the values of the member variables of object obj1 to 5 and 7
respectively and those of the
member variables of object obj2 to 10 and 15 respectively.
iii.
Create object objR of the class Demo1 such that the value of each of its
member variables is the
sum of the values of the corresponding member variables of the objects
obj1 and obj2 by calling
function addDemo1( ) defined in part a. Exercise C5*
Using the definition of the class Demo1 given in example C1, do the
following:
a. Write a void function updateDemo1 that receives as argument an
object of the class Demo1 and adds
10 to the value of its first member variable, and subtract 5 from the value
of its second member
variable.
b. Write a code segment to do the following: Declare object obj of the
class Demo1. Set the values of the member variables of object obj to 15
and 70 respectively. Add 10 to the value of the first member variable of
object obj and subtract 5 from the value of
its second member variable by calling the function updaDemo1( )
defined in part a. ©2011 Gilbert Ndjatou Page 216 Exercise C6
The class Demo2 is defined as follows:
class Demo2
{
public:
void setValues(double num1, double num2); // to set the values of both
member variables
double getValue1(void);
// to return the value of member variable val1
double getValue2(void);
// to return the value of member variable val2
double getAverage( );
// to compute the average of the values of both variables
private:
double val1;
// the first data member
double val2;
// the second data member
};
/*---------------------------------- function setValues( )
--------------------------------------------------*/
/* set the values of the member variables to the given values
*/
void Demo2:: setValues(double num1, double num2)
{
val1 = num1;
val2 = num2;
}
/*---------------------------------- function getValue1( )
--------------------------------------------------*/
/* returns the value of the first member variable
*/
double Demo2:: getValue1(void)
{
return (val1);
}
/*---------------------------------- function getValue2( )
--------------------------------------------------*/
/* returns the value of the second member variable
*/
double Demo2:: getValue2(void)
{
return (val2);
}
/*---------------------------------- function getAverage( )
--------------------------------------------------*/
/* compute the average of both values and return it
*/
double Demo2:: getAverage(void)
{
return( (valu1 + valu2) / 2);
}
©2011 Gilbert Ndjatou Page 217 Use the definition of the class Demo2
to do the following:
1. Declare object item of the class Demo2.
2. Read the values for the member variables of object item, and set the
values of its member variables.
3. Compute the average of the values of the member variables of object
item and print it.
4. Write a function named addDemo2( ) that receives as arguments two
objects of the class Demo2 and
then builds and returns another object of the class Demo2 such that the
value of each of its member
variables is the sum of the values of the corresponding member variables
of its arguments.
5. Write the sequence of statements to do the following:
i.
Declare object obj1 and set its member variables to 5 and 7 respectively
ii.
Declare object obj2 and set its member variables to 14 and 9
respectively.
iii. Create a third object named objR such that the value of each of its
member variables is the sum
of the values of the corresponding member variables of objects obj1 and
obj2 by calling function
addDemo2( ).
6. Write a function incrDemo2 that receives as argument an object of the
class Demo2 and increments
the value of each of its member variables by 5.
7. Write the statement(s) to increment the value of each member variable
of object obj1 by 5 by calling
function incrDemo2( ). ©2011 Gilbert Ndjatou Page 218 Object-
Oriented Programming Object-Oriented programming is a programming
methodology with the following three fundamental
characteristics: Data abstraction and information hiding Inheritance
Dynamic binding of the messages (function calls) to the methods
(definitions of functions) Data abstraction and information hiding The
data is encapsulated with its processing methods (functions) with a
controlled access to the
data. Inheritance The definition of a new class (called derived class) can
be derived from that of an existing class
(called base class). Inheritance provides an effective way to reuse
programming code. Example: the class to represent graduate students
can be derived from the class to represent
students. Dynamic (run-time) Binding of the Messages to the Methods
Messages (function calls) are dynamically bound to specific method
(function) definitions: it
means that they are bound during the execution of the program. Data
Abstraction and Information Hiding in C++ Data abstraction and
information hiding is implemented in C++ by using classes as follows:
1. Make all data members of a class private.
2. For each data member, provide a public member function called set
function or mutator that a
user of the class must call to modify or set its value.
3. For each data member, provide a public member function called get
function or accessor that a
user of the class must call to access or obtain its value. ©2011 Gilbert
Ndjatou Page 219 Example O1
class Demo3
{
public:
void readValues(void);
void setValue1(double num);
void setValue2(double num);
double getValue1(void);
double getValue2(void);
double getAverage( );
private:
double computeSum( );
double val1;
double val2;
}; // to read the values of the member variables
// to set the value of the first member variable
// to set the value of the second member variable
// to return the value of the first member variable
// to return the value of the second member variable
// to compute the average of both values
// to compute the sum of both values
// the first member variable
// the second member variable /*---------------------------------- function
readValues( ) --------------------------------------------------*/
/* read the values of the member variables
--------------------------------------------------------------*/
void Demo3:: readValues(void)
{
cin >> val1 >> val2;
} /*---------------------------------- function getValue1( )
--------------------------------------------------*/
/* return the value of the first member variable
------------------------------------------------------*/
double Demo3:: getValue1(void)
{
return (val1);
} /*---------------------------------- function setValue1( )
--------------------------------------------------*/
/* set the value of the first member variable to the given value
-------------------------------------*/
void Demo3:: setValue1(double num)
{
val1 = num;
} ©2011 Gilbert Ndjatou Page 220 /*----------------------------------
function getValue2( ) --------------------------------------------------*/
/* return the value of the second member variable
--------------------------------------------------*/
double Demo3:: getValue2(void)
{
return (val2);
} /*---------------------------------- function setValue2( )
--------------------------------------------------*/
/* set the value of the second member variable to the given value
*/
void Demo3:: setValue2(double num)
{
val2 = num;
} /*---------------------------------- function getAverage( )
--------------------------------------------------*/
/* compute the average of both values and return it
----------------------------------------------------*/
double Demo3:: getAverage(void)
{
double total;
total = computeSum( );
return(total / 2);
} /*---------------------------------- function computeSum( )
--------------------------------------------------*/
/* compute the sum of both values and return it
----------------------------------------------------------*/
double Demo3:: computeSum(void)
{
return (val1 + val2 ) ;
} /*------ The following code segment defines an object of the class
Demo3,
reads values for its member variables, and computes and prints their
average -----------------*/
Demo3 item1;
item1.readValues( );
cout << endl << “The avareage of:t”
<< item1.getValue1( ) << “ and “
<< item1.getValue2( ) << “ is: “
<< item1.getAverage( );
©2011 Gilbert Ndjatou // read the values for the member variables
// output the first value
// output the second value
// output their average
Page 221 /*------ The following code segment defines an object of the
class Demo3,
sets the values for its members variables to 57 and 86, and computes and
prints their average --*/
Demo3 item2;
item2.setValue1(57 );
// set the value of the first member variable to 57
item2.setValue2(86 );
// set the value of the second member variable to 86
cout << endl << “The avareage of:t”
<< item2.getValue1( ) << “ and “ // output the first value
<< item2.getValue2( ) << “ is: “
// output the second value
<< item2.getAverage( );
// output their average Notes
1. You do not have to define a set function for each member variable:
this is usually the case when the
member variable is initialized or its value is input and will not be
modified.
2. A set function may be used to set the values of two or more member
variables. For example, the
class Demo3 of example O1 could only have one set function setValues
(double num1, double
num2) that sets the values of both member variables of an object instead
of the two set functions
setVal1( double num ) and setVal2( double num ).
3. You do not have to define a get function for each member variable:
this is usually the case when the
value of the member variable is not needed by the user of the class.
4. The essence of object-oriented programming is to solve a problem as
follows:
a. First identify the real world objects of that problem and the processing
required of each object.
b. Then create those objects simulations and processes, and the required
communications between
them. Initializing Object with constructors A constructor is a special
member function of a class that is used to initialize the member variables
of the objects of that class. A constructor of a class has the following
characteristics:
1. Its name is the same as the name of the class.
2. It has no return type (not even void).
3. It may or may not have parameters. A class may have more than one
constructor, and A constructor of a class is automatically called when an
object of that class is created. ©2011 Gilbert Ndjatou Page 222 Default
Constructor The default constructor of a class is the constructor with no
parameters. The default constructor of a class is called when an object of
that class is defined without initial
values. When you define a class without any constructor, the compiler
creates the default constructor for that
class. The default constructor created by the compiler does nothing. If
you define a class with at least one constructor, you must also define the
default constructor for
that class if you want to define objects of that class without initial
value(s): the compiler does not
create a default constructor for a class that has another constructor.
Example O2
The following class named Demo4 is the class Demo3 of example O1 to
which we have added the
default constructor.
class Demo4
{
public:
Demo4( );
void readValues(void);
void setValue1(double num);
void setValue2(double num);
double getValue1(void);
double getValue2(void);
double getAverage( );
private:
double computeSum( );
double val1;
double val2;
}; // default constructor
// to read the values of the member variables
// to set the value of the first member variable
// to set the value of the second member variable
// to return the value of the first member variable
// to return the value of the second member variable
// to compute the average of both values
// to compute the sum of both values
// the first member variable
// the second member variable /*--------------------------Definition of the
default constructor-------------------------------------------*/
Demo4 :: Demo4( )
{
val1 = 0;
val2 = 0;
} ©2011 Gilbert Ndjatou Page 223 /*------------------------------ Ex...
************************************************

More Related Content

What's hot

Interfaces in JAVA !! why??
Interfaces in JAVA !!  why??Interfaces in JAVA !!  why??
Interfaces in JAVA !! why??vedprakashrai
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4Vince Vo
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manualqaz8989
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interfacemanish kumar
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1Chris Huang
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2Chris Huang
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++Mohamad Al_hsan
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Liju Thomas
 
重構—改善既有程式的設計(chapter 9)
重構—改善既有程式的設計(chapter 9)重構—改善既有程式的設計(chapter 9)
重構—改善既有程式的設計(chapter 9)Chris Huang
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
Oop02 6
Oop02 6Oop02 6
Oop02 6schwaa
 
Refactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsRefactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsfungfung Chen
 

What's hot (20)

Interfaces in JAVA !! why??
Interfaces in JAVA !!  why??Interfaces in JAVA !!  why??
Interfaces in JAVA !! why??
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manual
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
06 inheritance
06 inheritance06 inheritance
06 inheritance
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
重構—改善既有程式的設計(chapter 9)
重構—改善既有程式的設計(chapter 9)重構—改善既有程式的設計(chapter 9)
重構—改善既有程式的設計(chapter 9)
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Inheritance
InheritanceInheritance
Inheritance
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Lecture5
Lecture5Lecture5
Lecture5
 
Oop02 6
Oop02 6Oop02 6
Oop02 6
 
Refactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsRefactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objects
 

Similar to Introduction to Classes in 40 Characters

Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)nirajmandaliya
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Lecture13 abap on line
Lecture13 abap on lineLecture13 abap on line
Lecture13 abap on lineMilind Patil
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdfKUNALHARCHANDANI1
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08Jotham Gadot
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++Swarup Boro
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentationnafisa rahman
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsMarlom46
 
Lecture 5 Inheritance
Lecture 5 InheritanceLecture 5 Inheritance
Lecture 5 Inheritancebunnykhan
 
C questions
C questionsC questions
C questionsparm112
 

Similar to Introduction to Classes in 40 Characters (20)

Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Lecture13 abap on line
Lecture13 abap on lineLecture13 abap on line
Lecture13 abap on line
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdf
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
Savitch ch 10
Savitch ch 10Savitch ch 10
Savitch ch 10
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Object and class presentation
Object and class presentationObject and class presentation
Object and class presentation
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Object & classes
Object & classes Object & classes
Object & classes
 
Savitch Ch 10
Savitch Ch 10Savitch Ch 10
Savitch Ch 10
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
DS Unit 6.ppt
DS Unit 6.pptDS Unit 6.ppt
DS Unit 6.ppt
 
Lecture 5 Inheritance
Lecture 5 InheritanceLecture 5 Inheritance
Lecture 5 Inheritance
 
C questions
C questionsC questions
C questions
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Introduction to Classes in 40 Characters

  • 1. Introduction to Classes The concept of a class FOR MORE CLASSES VISIT tutorialoutletdotcom Introduction to Classes The concept of a class is the same as that of a structure: it is a user-defined data type that is used to create a group of variables that may have different data types. In addition to the data members, a member of a class can also be a function. A member function is in general specified in the class definition by its function prototype with its definition provided somewhere else in the program. You define a class as follows: class <class-name> { <Data-members-and/or-member functions-declarations> }; A member of a class (data or function) can be public or private. In the definition of a class, you use the label public to specify its public members and the label private to specify its private members. Example C1 class Demo1 { public: double getValue2(void);
  • 2. void setValue2(double num); double getAverage( ); double val1; private: double computeSum( ); double val2; // to return the value of the private data member // to set the value of the private data member // to compute the average of both values // the public data member // to compute the sum of both values // the private data member }; ©2011 Gilbert Ndjatou Page 207 Definition of a Class Member Function When you write the definition of a class member function, you must precede the name of the function in the function header by the name of that class followed by the scope resolution operator ( :: ). A class data member (public or private) can be accessed in the body of a member function of that class. A class member function (private or public) can be called in another member function of that class. Example C2 Definitions of the member functions of class Demo1: /*---------------------------------- function getValue2( ) --------------------------------------------------*/ /* returns the value of the private member variable */
  • 3. double Demo1:: getValue2(void) { return (val2); } /*---------------------------------- function setValue2( ) --------------------------------------------------*/ /* set the value of the private member variable to the given value */ void Demo1:: setValue2(double num) { val2 = num; } /*---------------------------------- function getAverage( ) --------------------------------------------------*/ /* compute the average of both values and return it */ double Demo1:: getAverage(void) { double total; total = computeSum( ); return(total / 2);
  • 4. } /*---------------------------------- function computeSum( ) ------------------------------------------------*/ /* compute the sum of both values and return it */ double Demo1:: computeSum(void) { return (val1 + val2 ) ; } ©2011 Gilbert Ndjatou Page 208 Declaration of a Class Variable (or Object) A class variable is called object. You declare an object in the same way that you declare a structure variable. As with structure variables, when you declare an object, a member variable is created for each data member of the class. Example C3 Declaration Effects in Memory Demo1 item1; item1.val1 item1.val2 Demo1 item2; item2.val1 item2.val2 Specifying the Members of an Object You specify an object’s public member variable in the same way that you specify a member of a structure variable, by using the dot operator. You call a class public member function on an object by preceding the function call with the name of that object, followed by the dot operator. A private member variable of an object can only be specified in a member function or a friend
  • 5. function of the class of that object. A private member function of a class can be called on an object only in a member function or a friend function of the class of that object. A class member function can be called in a function that is not a class member function only on an object. Example C4 Given the class Demo1 of example C1 and object item1 defined in function main as follows: Demo1 item1; ©2011 Gilbert Ndjatou Page 209 We have the following access to the member functions and the member variable of object item1: Valid Access to the Members of Object item1 1. cin >> item1.val1; 2. item1.setValue2 (15); 3. cout << endl << “The average of:t” 4. << item1.val1 << “ and “ 5. << item1.getValue2( ) << “ is: “ 6. << item1.getAverage( ); Invalid Access to the Members of Object item1 1. cin >> item1.val2; 2. item1.computeSum( );
  • 6. 3. getValue2( ); Effects // read a value into the public member variable val1 // set the private member variable val2 to 15 // output the value of the member variable val1 // output the value of the member variable val2 // output the average of the values of both variables Reasons // val2 is a private member variable // computeSum is a private member function /* in a function that is not a class member function, a class member function must be called on an object */ Objects and the Assignment Operator It is legal in C++ to assign an object to another object of the same class. The assignment of an object to another generates the member-wise assignments of the member variables of both objects. Example C5 Given the class Demo1 of Example C1 and the following definitions of objects: The assignment: Demo1 item1, item2; item1 = item2; has the same effect as: item1.val1 = item2.val1; item1.setValue2( item2.getValue2( ) ); Notes 1. The concept of combining a number of items such as variables and functions into a package such as an object is called encapsulation.
  • 7. 2. In a class definition, you can have any number of occurrences of the labels public: and private: as shown in the following example: ©2011 Gilbert Ndjatou Page 210 class SampleClass { Public: void inputSomething( ); int stuff; private: int computeResult( int val); int val1; public: int setvalue( ); int val2; }; 3. In a class definition, the section between the opening brace { and the first access-specifier label, public: or private: is a private section. For example, the following two class definitions are identical: class SampleClass1
  • 8. { int computeResult( int val); int val1; public: int setvalue( ); int val2; }; class SampleClass2 { private: int computeResult( int val); int val1; public: int setvalue( ); int val2; }; 4. It is a common practice to specify the public members of a class before the private members and to list the member function prototypes before the member variables as we have done with the definition of the class Demo1 of Example C1. ©2011 Gilbert Ndjatou Page 211 Exercise C1* Given the following class definition:
  • 9. class Automobile { public: void setPrice ( double newPrice ); void setProfit ( double newProfit ); double getPrice ( ); private: double price; double profit; double getProfit ( ); }; // to set the value of price member variable // to set the value of profit member variable // to return the value of price member variable // to return the value of profit member variable a. Write the definitions of the member functions setPrice, setProfit, getPrice, and getProfit. b. Given the following definitions of objects hyundai and jaguar in function main: Automobile hyunday, jaguar; Which of the following statements are invalid? Also provide the reasons why a statement is invalid. hyunday.price = 15000.00;
  • 10. jaguar.setPrice( 45000.00 ); cout << jaguar.getProfit ( ); jaguar.setProfit( ); cout << jaguar.getPrice ( ); jaguar = hyunday; setPrice ( 16500 ); c. d. e. f. Write a statement to set the profit member variable of object jaguar to 3500. Write a statement to read a price and set the price member variable of object hyunday to it. Write a statement to output the value of the price member variable of object jaguar. Is it possible to write a statement to output the value of the profit member variable of objet jaguar? Why? g. Write the statements to do the following: 1. Assign the value of each member variable of object jaguar to the corresponding member variable of object hyunday, and then, 2. Change the value of the member variable price of object hyunday to 24000.00. ©2011 Gilbert Ndjatou Page 212 Exercise C2
  • 11. Given the following class Automobile defined in exercise C1: class Automobile { public: void setPrice ( double newPrice ); void setProfit ( double newProfit ); double getPrice ( ); private: double price; double profit; double getProfit ( ); }; // to set the value of price member variable // to set the value of profit member variable // to return the value of price member variable // to return the value of profit member variable a. And given the following definitions of objects sable and jeep in function main: Automobile sable, jeep; Which of the following statements are invalid? Also provide the reasons why a statement is invalid. cin >> jeep.profit;
  • 12. jeep.setPrice( 45000.00 ); cout << jeep.getProfit ( ); cout << jeep.getPrice ( ); sable.setProfit( ); jeep = sable; cout << getPrice( ); b. c. d. e. Write a statement to set the price member variable of object jeep to 22000.00. Write a statement to read a profit and set the profit member variable of object sable to it. Write a statement to output the value of the price member variable of object jeep. Write the statements to assign the value of each member variable of object jeep to the corresponding member variable of object sable, and then to change the value of member variable profit of object sable to 4000.00. Exercise C3 Write the definition of function main that does the following: a. Define an object of the class Demo1 (defined in example C1above)
  • 13. b. Read two values and set the two member variables of this object to those values. c. Output the values of the member variables of this object with appropriate messages. d. Compute and print the average value of the member variables of this object with an appropriate message. ©2011 Gilbert Ndjatou Page 213 Classes and Functions A class can be the return type of a function: a function can return an object. Example C6 The following function reads the values for the two member variables of an object of the type class Demo1 (defined in example C1 above) and then returns that object. Demo1 inputValues (void) { Demo1 temp; double num; cin >> temp.val1; // read a value for the first member variable of the object /*--- read the second value and set the second member variable of the object to it--------*/ cin >> num; temp.setValue2(num); return (temp);
  • 14. } /*----------------------------------- the above function is called as follows ---------------------------*/ Demo1 item; item = inputValues( ); An object can be a value parameter of a function. When a function with an object as value parameter is called, the value of each member variable of the object argument is copied to the corresponding member variable of the object parameter. Example C7 The following function receives an object of the class Demo1 (defined in example C1 above) as argument, and returns five times the average of the values of its member variables. double average5 (Demo1 item ) { double result; result = 5 * item.getAverage( ); return result; } ©2011 Gilbert Ndjatou Page 214 /*------------------------ the above function may be called as follows ---------------------------*/ Demo1 stuff; stuff.val1 = 10; stuff.setValue2 ( 12 );
  • 15. cout << endl << average5( stuff ); After this call of function average5( ), its body is executed as if it was written as follows: double average5 (Demo1 item ) { item.val1 = stuff.val1; item.setValue2( stuff.getValue2( ) ); double result; result = 5 * item.getAverage( ); return result; } An object can be a reference parameter of a function. When a function with an object as a reference parameter is called, the object argument replaces the object parameter in the body of the function. Example C8 The following function receives an object of the class Demo1 (defined in example C1 above) as argument, and adds 3 to the value of each of its member variables. void add3 (Demo1 &item) { int num; item.val1 += 3; num = item.getValue2( );
  • 16. item.setValue2( num + 3 ); } /*----------------------------------- the above function is called as follows ---------------------------*/ Demo1 someItem; someItem.val1 = 10; someItem.setValue2 ( 15 ); add3( someItem ); // someItem.value1 = 13 and someItem.value2 = 18 ©2011 Gilbert Ndjatou Page 215 After the above call of function add3( ), its body is executed as if it was written as follows: { int num; someItem.val1 += 3; num = someItem.getValue2( ); someItem.setValue2( num + 3 ); } Exercise C4* Using the definition of the class Demo1 given in example C1, do the following: a. Write a function addDemo1 that receives as arguments two objects of the class Demo1 and then builds and returns another object of the class Demo1 such that the value of each of its member
  • 17. variable of is the sum of the values of the corresponding member variables of the objects received as arguments. b. Write a code segment to do the following: i. Declare objects obj1 and obj2 of the class Demo1. ii. Set the values of the member variables of object obj1 to 5 and 7 respectively and those of the member variables of object obj2 to 10 and 15 respectively. iii. Create object objR of the class Demo1 such that the value of each of its member variables is the sum of the values of the corresponding member variables of the objects obj1 and obj2 by calling function addDemo1( ) defined in part a. Exercise C5* Using the definition of the class Demo1 given in example C1, do the following: a. Write a void function updateDemo1 that receives as argument an object of the class Demo1 and adds 10 to the value of its first member variable, and subtract 5 from the value of its second member variable.
  • 18. b. Write a code segment to do the following: Declare object obj of the class Demo1. Set the values of the member variables of object obj to 15 and 70 respectively. Add 10 to the value of the first member variable of object obj and subtract 5 from the value of its second member variable by calling the function updaDemo1( ) defined in part a. ©2011 Gilbert Ndjatou Page 216 Exercise C6 The class Demo2 is defined as follows: class Demo2 { public: void setValues(double num1, double num2); // to set the values of both member variables double getValue1(void); // to return the value of member variable val1 double getValue2(void); // to return the value of member variable val2 double getAverage( ); // to compute the average of the values of both variables private: double val1; // the first data member double val2;
  • 19. // the second data member }; /*---------------------------------- function setValues( ) --------------------------------------------------*/ /* set the values of the member variables to the given values */ void Demo2:: setValues(double num1, double num2) { val1 = num1; val2 = num2; } /*---------------------------------- function getValue1( ) --------------------------------------------------*/ /* returns the value of the first member variable */ double Demo2:: getValue1(void) { return (val1); } /*---------------------------------- function getValue2( ) --------------------------------------------------*/
  • 20. /* returns the value of the second member variable */ double Demo2:: getValue2(void) { return (val2); } /*---------------------------------- function getAverage( ) --------------------------------------------------*/ /* compute the average of both values and return it */ double Demo2:: getAverage(void) { return( (valu1 + valu2) / 2); } ©2011 Gilbert Ndjatou Page 217 Use the definition of the class Demo2 to do the following: 1. Declare object item of the class Demo2. 2. Read the values for the member variables of object item, and set the values of its member variables. 3. Compute the average of the values of the member variables of object item and print it.
  • 21. 4. Write a function named addDemo2( ) that receives as arguments two objects of the class Demo2 and then builds and returns another object of the class Demo2 such that the value of each of its member variables is the sum of the values of the corresponding member variables of its arguments. 5. Write the sequence of statements to do the following: i. Declare object obj1 and set its member variables to 5 and 7 respectively ii. Declare object obj2 and set its member variables to 14 and 9 respectively. iii. Create a third object named objR such that the value of each of its member variables is the sum of the values of the corresponding member variables of objects obj1 and obj2 by calling function addDemo2( ). 6. Write a function incrDemo2 that receives as argument an object of the class Demo2 and increments the value of each of its member variables by 5. 7. Write the statement(s) to increment the value of each member variable of object obj1 by 5 by calling
  • 22. function incrDemo2( ). ©2011 Gilbert Ndjatou Page 218 Object- Oriented Programming Object-Oriented programming is a programming methodology with the following three fundamental characteristics: Data abstraction and information hiding Inheritance Dynamic binding of the messages (function calls) to the methods (definitions of functions) Data abstraction and information hiding The data is encapsulated with its processing methods (functions) with a controlled access to the data. Inheritance The definition of a new class (called derived class) can be derived from that of an existing class (called base class). Inheritance provides an effective way to reuse programming code. Example: the class to represent graduate students can be derived from the class to represent students. Dynamic (run-time) Binding of the Messages to the Methods Messages (function calls) are dynamically bound to specific method (function) definitions: it means that they are bound during the execution of the program. Data Abstraction and Information Hiding in C++ Data abstraction and information hiding is implemented in C++ by using classes as follows: 1. Make all data members of a class private. 2. For each data member, provide a public member function called set function or mutator that a user of the class must call to modify or set its value. 3. For each data member, provide a public member function called get function or accessor that a user of the class must call to access or obtain its value. ©2011 Gilbert Ndjatou Page 219 Example O1
  • 23. class Demo3 { public: void readValues(void); void setValue1(double num); void setValue2(double num); double getValue1(void); double getValue2(void); double getAverage( ); private: double computeSum( ); double val1; double val2; }; // to read the values of the member variables // to set the value of the first member variable // to set the value of the second member variable // to return the value of the first member variable // to return the value of the second member variable // to compute the average of both values // to compute the sum of both values
  • 24. // the first member variable // the second member variable /*---------------------------------- function readValues( ) --------------------------------------------------*/ /* read the values of the member variables --------------------------------------------------------------*/ void Demo3:: readValues(void) { cin >> val1 >> val2; } /*---------------------------------- function getValue1( ) --------------------------------------------------*/ /* return the value of the first member variable ------------------------------------------------------*/ double Demo3:: getValue1(void) { return (val1); } /*---------------------------------- function setValue1( ) --------------------------------------------------*/ /* set the value of the first member variable to the given value -------------------------------------*/ void Demo3:: setValue1(double num) { val1 = num;
  • 25. } ©2011 Gilbert Ndjatou Page 220 /*---------------------------------- function getValue2( ) --------------------------------------------------*/ /* return the value of the second member variable --------------------------------------------------*/ double Demo3:: getValue2(void) { return (val2); } /*---------------------------------- function setValue2( ) --------------------------------------------------*/ /* set the value of the second member variable to the given value */ void Demo3:: setValue2(double num) { val2 = num; } /*---------------------------------- function getAverage( ) --------------------------------------------------*/ /* compute the average of both values and return it ----------------------------------------------------*/ double Demo3:: getAverage(void) { double total; total = computeSum( );
  • 26. return(total / 2); } /*---------------------------------- function computeSum( ) --------------------------------------------------*/ /* compute the sum of both values and return it ----------------------------------------------------------*/ double Demo3:: computeSum(void) { return (val1 + val2 ) ; } /*------ The following code segment defines an object of the class Demo3, reads values for its member variables, and computes and prints their average -----------------*/ Demo3 item1; item1.readValues( ); cout << endl << “The avareage of:t” << item1.getValue1( ) << “ and “ << item1.getValue2( ) << “ is: “ << item1.getAverage( ); ©2011 Gilbert Ndjatou // read the values for the member variables // output the first value // output the second value // output their average
  • 27. Page 221 /*------ The following code segment defines an object of the class Demo3, sets the values for its members variables to 57 and 86, and computes and prints their average --*/ Demo3 item2; item2.setValue1(57 ); // set the value of the first member variable to 57 item2.setValue2(86 ); // set the value of the second member variable to 86 cout << endl << “The avareage of:t” << item2.getValue1( ) << “ and “ // output the first value << item2.getValue2( ) << “ is: “ // output the second value << item2.getAverage( ); // output their average Notes 1. You do not have to define a set function for each member variable: this is usually the case when the member variable is initialized or its value is input and will not be modified. 2. A set function may be used to set the values of two or more member variables. For example, the class Demo3 of example O1 could only have one set function setValues (double num1, double
  • 28. num2) that sets the values of both member variables of an object instead of the two set functions setVal1( double num ) and setVal2( double num ). 3. You do not have to define a get function for each member variable: this is usually the case when the value of the member variable is not needed by the user of the class. 4. The essence of object-oriented programming is to solve a problem as follows: a. First identify the real world objects of that problem and the processing required of each object. b. Then create those objects simulations and processes, and the required communications between them. Initializing Object with constructors A constructor is a special member function of a class that is used to initialize the member variables of the objects of that class. A constructor of a class has the following characteristics: 1. Its name is the same as the name of the class. 2. It has no return type (not even void). 3. It may or may not have parameters. A class may have more than one constructor, and A constructor of a class is automatically called when an object of that class is created. ©2011 Gilbert Ndjatou Page 222 Default Constructor The default constructor of a class is the constructor with no parameters. The default constructor of a class is called when an object of that class is defined without initial values. When you define a class without any constructor, the compiler creates the default constructor for that
  • 29. class. The default constructor created by the compiler does nothing. If you define a class with at least one constructor, you must also define the default constructor for that class if you want to define objects of that class without initial value(s): the compiler does not create a default constructor for a class that has another constructor. Example O2 The following class named Demo4 is the class Demo3 of example O1 to which we have added the default constructor. class Demo4 { public: Demo4( ); void readValues(void); void setValue1(double num); void setValue2(double num); double getValue1(void); double getValue2(void); double getAverage( ); private: double computeSum( );
  • 30. double val1; double val2; }; // default constructor // to read the values of the member variables // to set the value of the first member variable // to set the value of the second member variable // to return the value of the first member variable // to return the value of the second member variable // to compute the average of both values // to compute the sum of both values // the first member variable // the second member variable /*--------------------------Definition of the default constructor-------------------------------------------*/ Demo4 :: Demo4( ) { val1 = 0; val2 = 0; } ©2011 Gilbert Ndjatou Page 223 /*------------------------------ Ex... ************************************************