Classes and Objects
Classes and Objects
Allows
bundling of related variables (member
data) and the functions that operate on them
(member functions)
Describes the properties that all instances of the
class will have
object: an instance of a class, in the same
way that a variable can be an instance of a
struct
OBJECT-ORIENTED PROGRAMMING
TERMINOLOGY
int side;
Member functions
void setSide(int s)
int getSide()
Square object’s functions: setSide - set the size of the side of the
required ;
ACCESS SPECIFIERS
Used to control access to members of the
class.
Each member is declared to be either
public: can be accessed by functions
outside of the class
or
private: can only be called by or accessed
by functions that are members of
the class
CLASS EXAMPLE
class Square
{
private:
Access specifiers int side;
public:
void setSide(int
s)
{ side = s; }
int getSide()
{ return side; }
};
MORE ON ACCESS
SPECIFIERS
class Square
{
private:
int side;
public:
void setSide(int s)
inline functions { side = s; }
int getSide()
{ return side; }
};
DEFINING MEMBER FUNCTIONS AFTER
THE CLASS DECLARATION *PREFERRED WAY
public:
Square(int s = 1) // default
{ side = s; } // constructor
// Other member
// functions go here
};
OVERLOADING CONSTRUCTORS
A class can have more than 1 constructor
Overloaded constructors in a class must have
different parameter lists
Square();
Square(int);
THE DEFAULT CONSTRUCTOR
Constructors can have any number of
parameters, including none
A default constructor is one that
takes no arguments either due to
No parameters or
All parameters have default values
public:
Square() // default
{ side = 1; } // constructor
// Other member
// functions go here
};
ANOTHER DEFAULT CONSTRUCTOR EXAMPLE
class Square
{
private: Has parameter
value
public:
Square(int s = 1) // default
{ side = s; } // constructor
// Other member
// functions go here
};
INVOKING A CONSTRUCTOR
To create an object using the default
constructor, use no argument list and no ()
Square square1;
To create an object using a constructor that has
parameters, include an argument list
Square square2(8);
DESTRUCTORS
Are public member functions that
are automatically called when
objects are destroyed
The destructor name is
~className, e.g., ~Square
It has no return type
It takes no arguments
Only 1 destructor is allowed per
class
(i.e., it cannot be overloaded)
PRIVATE MEMBER
FUNCTIONS