You are on page 1of 27

C++ Class & Object

Presented By: Muhammad Farhan Niaj Neebir


Overview: Class & Object

● Member variables & member functions.


● An object is an instantiation of a class.
● Access specifiers: public, protected & private. (private by default)
● Special specifier: friend
Class & Objects: Example
Access Specifiers
Class vs Structure

● Members are private by default in a class but are public


in a struct.
● The convention is that struct is used for storing data
only where class is used for storing both data &
function.
Objects: on the Stack vs on the Heap
Constructors

A constructor is specified by a method name


that is the same as the class name. A
constructor never has a return type and may or
may not have parameters.
How to Declare & Use
Default Constructor

● If you don’t define any constructor, compiler will declare one for you. This
is compiler-generated default constructor.
● If you declare a constructor which takes no argument then it is explicitly
defaulted constructor.
● With compiler-generated default constructor, you can’t declare array of
objects.
Explicitly Deleted Constructor
Constructor Initializer
Copy Constructor
When called?

● Initialize one object from another of the same type.


● Copy an object to pass it as an argument to a function.
● Copy an object to return it from a function.
Why needed?
Delegating Constructor
class Sample
{
public:
Sample() : r(0), i(0) {}
Sample(double real) : r(real), i(0){}

Sample(double real, double img) : r(real), i(img){}


Sample(double data[2]) : r(data[0]), i(data[1]){}

private:
double r;
double i;
};
class Sample {
Private:

Sample(double real, double img) : r(real), i(img){}


public:
Sample() : Sample(0.0){}

Sample(double real) : Sample(real,0){}

Sample(double data[2]): Sample(data[0], data[1]){}

private:
double r;
double i;
};
Destructor
Data Member: Static Types
const Data Members
Static Methods
const Methods
Mutable Data Members

Sometimes you write a method that is “logically” const but happens to change a
data member of the object. This modi cation has no effect on any user-visible
data, but is technically a change, so the compiler won’t let you declare the
method const. For example, suppose that you want to pro le your spreadsheet
application to obtain info about how often data is being read. A crude way to do
this would be to add a counter to the SpreadsheetCell class that counts each
call to getValue() or getString(). Unfortunately, that makes those methods
non-const in the compiler’s eyes, which is not what you intended. The solution
is to make your new counter variable mutable, which tells the compiler that it’s
okay to change it in a const method.
Inline Methods

➢ What is inline methods?


➢ Advantages.
➢ When to & when not to use?
Building Stable Interfaces

➢ How to?
➢ Advantages.
Reference

Professional C++ (3rd Edition)

➔ Marc Gregoire

(Chapter- 7, 8)

You might also like