Classes in C++ Full
Classes in C++ Full
Introduction
Private :- Accessed only by the functions within the class not outside
the class
• Private functions – they are called by other member functions only
• Default :- private
Public
Data or functions can be directly referenced outside the class
Example
Declaration of fraction class
class Fraction
{
private:
int numerator;
int denominator;
public :
void store(int numer , int denom);
void print ();
};
Scope Resolution operator
• Syntax :-
Class_name ::member_name
• To refer to not in the current scope
Book img
i.e function definition is out of scope as it is defined
outside the class
Class Objects
We declare objects of a class with exactly the same sort of declaration that we
declare variables of basic types.
• Example
Fraction fr;
Accessing member Object
COPY
CONSTRUCTOR
CONSTRUCTOR
DESTRUCTOR
The only functions in a class that are defined and declared without a
return value
CONSTRUCTOR
• They come into play when an object dies, either because it is no longer in scope
or because it has been deleted.
• Name of the destructor is the name of the class, preceded by (~)tilde.
• No return type.
• Destructor must have no parameters
• Cannot overload a destructor
• Class can have one ands only one destructor.
Eg :-
Fraction :: ~Fraction()
{ }
MUTATOR and ACCESSOR functions
Mutator function:-
A function that can change the state of the host object.
Fr1.store(4,9);
Accessor function:-
Cannot change the state of the invoking object.
An accessor is called either for its side effects such as to print or
for its return value.
Like mutators , accessor must always have a return type , even
if it is void.
Note