Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 37

Classes

Overview
 Header Files
 Accessing Class Members
 Class Scope
 Constructors/Destructors
 Member initializer list
 this Pointer
 Friend
 Static
 new/delete operators
Header Files
 Preprocessor Guards
 Prevent header files from being
included more than once

#ifndef FILENAME_H
#define FILENAME_H
. . .
#endif

 To include a standard library header file:


#include <standard_header>

 To include a local header file:


#include "my_file.h"
Person Example
 Create Person.h/Person.cpp for a Person
class with:
 name attribute of type string

 constructor that initializes name


 name has default value “Jane Doe”
 setName and getName functions
 preprocessor guards in Person.h

 Create main.cpp with function main


 Create a Person object named p
 Create a reference, pRef, to p
 Create a pointer, pPtr, to p
Person.h
#ifndef PERSON_H
#define PERSON_H

#include <string>
using std::string;

class Person {
public:

Person(const string name="Jane Doe");

void setName(const string name);


string getName();

private:
string _name;
};

#endif
Person.cpp
#include "Person.h"

Person::Person(const string name)


{
_name = name;
}

void Person::setName(const string name)


{
_name = name;
}

string Person::getName()
{
return _name;
}
main.cpp
#include <iostream>
using namespace std;

#include "Person.h"

int main()
{
Person p;
Person &pRef = p;
Person *pPtr = &p;

return 0;
}
Accessing a Class Member
 Dot (.) operator with an object:
objectName.memberFunction();

 Dot (.) operator with a reference


referenceName.memberFunction();

 Arrow (->) operator with a pointer


pointerName->memberFunction();

 In main.cpp, print object p’s name using p,


pPtr, and pRef

cout << p.getName() << endl;


cout << pRef.getName() << endl;
cout << pPtr->getName() << endl;
Class Scope
 Every class defines its own scope
 Class member functions and
member data are only known to
other member functions of the class
 Outside the class scope:
 Public members may be accessed
through a handle to a class object:
 Object
 Reference to an object
 Pointer to an object
Constructor & Destructor
 Constructor
 Called when an object is created
 May be overloaded

ClassName(optional_arg_list);

 Destructor
 Called when an object is destroyed
 Only one per class

~ClassName();

 Constructor/destructor is not called when


reference or pointer is created/destroyed
 If constructor/destructor is not provided,
compiler generates a default one
const Member Function
 Cannot modify the object upon which the
function is invoked
 Syntax:
class ClassName {

// const member function


rtnType func(argList) const;

};
const member non-const
function member function
const can invoke error
object member function
non-const can invoke can invoke
object member function member function
Person Example
 Which Person member functions should
be const?
 getName should be const

 Modify getName to be const:


 Person.h:

class Person {
...
string getName() const;

 Person.cpp:

string Person::getName() const


{
return _name;
}
Object Data Members
 Data members that are object of
other classes
 Called composition or has-a
relationship

 Person Example
 Person object has a string object
Member Initializer List
 Specifies initial values or constructor
arguments for data members of the class
 Specified in the constructor function:

ClassName::ClassName(argList)
: dataMember1(initialValue),
dataMember2(arg1, arg2)
{ ... }

 Executes before the body of the constructor


Data Members and Initializers
 Data members that must be initialized
with initializer list:
 Const data members
 Reference data members
 Object data members that require
arguments to their constructor

 Modify Person constructor to use


member initializer list:

Person::Person(const string name)


: _name(name)
{

}
Order of Construction
 Object data members are constructed in
the order they are declared in the class
definition
 Ordering in initializer list does not
impact order of construction
 Arguments to object data member’s
constructor is specified in member
initializer list of the enclosing object

 Object data members are constructed


before the enclosing object
this Pointer
 Implicit parameter of a member function
 Points to the object on which the member
function was invoked
 Pointer to an object of the class
 For example, we code:

object.func(a1, a2);

 Compiler treats the call as:

object.func(&object, a1, a2);

 &object is assigned to an implicit


parameter named this
Example Use of this Pointer
 To return a reference to the object
 Cascaded member function calls
 Dot operator (.) associates from left
to right:

obj.func1().func2().func3();

 func1, func2, and func3 need to return


a reference to obj

 Modify Person::setName to return a


reference to the Person object
Person Example
 Person.h:

Person& setName(const string name);

 Person.cpp:

Person& Person::setName(const string name)


{
_name = name;
return *this;
}

 Now setName and getName can be called


in the same expression in main.cpp:

cout << p.setName("B Poe").getName()


<< endl;
this Pointer and const
 In a const member function:
 Type of implicit this pointer is const
 Cannot modify the object upon which
the function is invoked
Store Example
 Create Store.h/Store.cpp for a Store class
with:
 owner attribute of type Person

 constructor that initializes owner


 setOwner and getOwner functions

 In function main:
 Create a Person object mrBox with
name “Mr Box”
 Create a Store object petStore with
owner mrBox
Store.h
#ifndef STORE_H
#define STORE_H

#include "Person.h"

class Store {
public:
Store(const Person owner);

void setOwner(const Person owner);


Person getOwner() const;

private:
Person _owner;
};

#endif
Store.cpp
#include "Store.h"

Store::Store(const Person owner)


: _owner(owner)
{
}

void Store::setOwner(const Person owner)


{
_owner = owner;
}

Person Store::getOwner() const


{
return _owner;
}
main.cpp
#include <iostream>
using namespace std;

#include "Person.h"
#include "Store.h"

int main()
{
...
...

Person mrBox("Mr Box");


Store petStore(mrBox);

return 0;
}
Friends
 Grants access to private members to
global functions or other classes

class ClassA {

// friend class
friend class ClassB;

// friend member function


friend returnType function(argList);

};

 Friend functions/classes can modify


private data members
Class Example
 Store::setOwnerName member function sets
the private _name attribute of a Person
object

void Store::setOwnerName(const string name)


{
_owner._name = name; // compile error
}

 To resolve compile error, declare Store to


be friend class of Person:

class Person {
friend class Store;
...
};
Class Example
 setStoreOwner global function accesses
private data member _owner of class Store:

void setStoreOwner(Store &s,


const Person &o)
{
s._owner = o; // compile error
}

 To resolve compile error, declare


setStoreOwner to be a friend of class Store:

class Store {
friend void setStoreOwner(Store &s,
const Person &o);
...
};
static Class Members
 Exist independently of any object of the
class:

class ClassName {

// static data member


static type dataMember;

// static member function


static returnType func(argList);

};

 Associated with the class, not with objects


of the class
static Data Member
 One copy of the variable is shared by all
objects of the class
 Exists when no objects of the class exist
 Declared in the class definition, normally
in ClassName.hpp:

class ClassName
{
static type staticData;
};

 Defined once outside the class body,


normally in ClassName.cpp:

type ClassName::staticData;
Store Example
 Add a _taxRate static data attribute of
type double to class Store.

 Store.h
class Store {
...
private:
Person _owner;
static double _taxRate;
};

 Store.cpp
#include "Store.h"

double Store::_taxRate;
Static Member Function
 Declare static inside the class definition:
class ClassName
{
static returnType func();
};

 Does not have a this pointer


 Cannot access non-static data members
 Cannot call non-static member functions
 Cannot be declared const
Class Example
 Add static setTaxRate member functions to
class Store:

 Store.h

class Store {
public:
...
static void setTaxRate(const double rate);

 Store.cpp

void Store::setTaxRate(const double rate)


{
_taxRate = rate;
}
Calling Static Member Function
 May be invoked using an object or with
the class name:

object.staticFunction();
ClassName::staticFunction();

 Invoke Store::setTaxRate member


function with and without a Store object:

 In function main:

petStore.setTaxRate(.10);
Store::setTaxRate(.08);
new and delete Operators
 Dynamic memory management operators
 Allow programmer to specify when to
create (allocate) and destroy (free)
objects
 Storage class rules do not apply to
objects created with operator new

 Dynamically allocate an object:

type *ptr = new type;


type *ptr = new type(arg1, arg2);

 Free a dynamically allocated object:


delete ptr;
Store Example
 Create a Store pointer named sPtr that
points to a dynamically allocated Store
object:

Store* sPtr = new Store(mrBox);

 Print out the owner’s name of the


dynamically allocated Store object:

cout << sPtr->getOwner().getName() << endl;

 Delete the dynamically allocated Store


object:

delete sPtr;
Dynamically Managing Arrays
 new and delete can dynamically allocate
and free arrays
 Specify size of arrays at runtime
instead of at compile time
 Dynamically allocate an array:

type *ptr = new type[ArraySize];

 Free a dynamically allocated array:

delete [] ptr;

 Note that delete ptr will only free first


element of an array
 must use delete [] ptr with an array
Person Example
 Set pPtr to point to a dynamically allocated
array of 10 Person objects:

pPtr = new Person[10];

 Print out the name of each Person in the


dynamically allocated array:

for (int i = 0; i < 10; ++i)


{
cout << pPtr[i].getName() << endl;
}

 Delete the dynamically allocated array:

delete [] pPtr;

You might also like