Classes and OOP
Class → a complex data type that groups data and related functions in the same structure
- Modelling the world with classes = more intuitive than with functions
- Like a struct → allows bundling of related variables
- BUT variables and functions in the class can have different properties than in a struct
Object → an instance of a class
- In the same way that a variable can be an instance of a struct
Attributes → member variables of a class
Methods/behaviours → member functions of a class
Procedural programming → data is separated from the functions
Data Hiding → restricting access to certain members of an object
- Making member variables private
Public interface → members of an object that are available outside of the object
- Member functions -> the class’ public interface
- The class interacts with the world via the public interface
Advantages of a public interface:
Eg. creating a class called Car that has accelerate() and brake() functions. The object user then calls the
functions but does not need to know how they work, just that they will.
Access Specifiers:
Used to control access to members of the class
Can be listed in any order in class definition
Can appear multiple times in class definition (eg. private: blah blah public: blah private:)
C++ → Default is private
Public → can be accessed by functions outside the class
Private → can only be called by or accessed by functions that are members of the class
Member functions:
Mutator → a member function that changes a private data member value in some way
Accessor → a function that retrieves a value from a private member variable without modifying it
- Const appears after parentheses in member function declaration = specifies the function will not
change any data in the calling object.
Eg. double getWidth() const;
Defining a member function:
Every class function belongs to the class
It can only be called on an object of that class
You can define member functions inside the class definition → inline functions
, Separating interface from implementation:
Header file: contains class definition and implementation
- Typically included multiple times (class def must be included by class implementation and driver
program) BUT must only be compiled once → use preprocessor (tell compiler to include header only
once)
- Use include guard → prevents header from being included more than once
Implementation file: includes header file and implements the class
Main.cpp: includes header file and instantiates objects of the class
Main.cpp and implementation file (.cpp) are compiled separately (-c) and linked together by the linker (-o)
- Driver program (main) can see public interface, but the implementation of the public interface is
hidden
Defining a member function: (outside the class)
Put prototype in class definition, in header file.
Define function using class name and scope resolution operator :: in implementation file (source-code file)
void Rectangle::setWidth(double w) {
width = w;
}
Make File:
Act1.out: Main.o Rectangle.o
g++ -std=c++98 Main.o Rectangle.o -o Act1.out
Main.o: Main.cpp
g++ -c -std=c++98 Main.cpp
Rectangle.o: Rectangle.cpp
g++ -c -std=c++98 Rectangle.cpp
run:
./Act1.out
clean:
rm *.o Act1.out
Defining an instance of a class: (object)
Defines on the stack like a struct variable
Eg. Rectangle r1;
,Access members using dot operator
Eg. r.getWidth()
Cannot access private members using dot operator → compile error
Eg. r.width = 5.35;
Cannot call class functions without an object → compile error
Eg. getWidth();
Pointer to an object:
Can define a pointer to an object
Rectangle r;
Rectangle *ptr = &r;
ptr->setLength(12);
Use a pointer to dynamically allocate an object
→ reserve required memory at run time, not compile time
Rectangle *rPtr = new Rectangle;
delete rPtr;
rPtr = NULL;
Create a dynamic object:
Rectangle *r = new Rectangle;
Rectangle *ptr; —> default constructor not called because no object is actually created.
Section 4.2
7.1 Function Overloading, default parameters, constructors
Function overloading
Overloaded functions → same name, different parameters, same return type
- Different parameter types, number of parameters
- CANNOT HAVE: same parameters, different return type
- Determined by function call, type and number of arguments
Compiler resolves call based on function signature
- Matches call with appropriate function
Rules for resolving overloading
1. Exact match: no automatic type conversion required
2. Match using automatic type conversion: if auto. conve. allows a match
a. 1: try promotion → int to double
b. 2: try type demotion → double to int
Default arguments
If argument missing in function call → default argument passed automatically to parameter
- Specified only in function prototype (in header file)
- Must appear first
Eg. int getSum(int a, int b = 0, int c = 0);
- When argument omitted from function call → all arguments to the right must also be omitted
Eg. sum = getSum(num1, , num3); → ERROR
Constructors
Objects → variables of a class type
, - Have private member variables → set using a constructor
Constructors: special member function, called automatically when object created
- Initialises an object → allocated memory, assigns values to private member variables
- Name = name of the class
- No return type
Default constructor: takes no arguments
- c++ generates for you UNLESS we define a constructor with arguments
- Allocates memory for new object → BUT no values assigned
Eg. Rectangle r;
- NOTE: Rectangle *ptr; → default constructor NOT called (no object created)
Rectangle::Rectangle() {
width = 1.0;
length = 1.0;
}
Constructors with arguments:
Rectangle r(10.0, 5.0);
Rectangle* rPtr = new Rectangle(15.0, 4.0);
Initialisation section → preferable way to handle constructor arguments
In constructor prototype:
Rectangle (double, double)
In constructor definition:
Rectangle::Rectangle(double w, double l)
: width(w), length(l)
{} → Can put additional code in member body
- Add parameter validation code
Rectangle::Rectangle(double w, double l)
: width(w), length(l) {
if ((width <= 0) || (length <= 0)) {
cout << "Invalid dimensions" <<endl;
exit(1);
}
}
Overloading constructors → must have different parameters
Default arguments: if all parameters have default arguments → works like default constructor if arguments
omitted
Eg. Rectangle(double w = 1.0, double l = 1.0);
Section 7.2
const Modifier, Inline, Static, UML
Parameter Passing Efficiency
Call/Pass-by-value: copies argument in call to parameter
- Inefficient for large data values (eg. objects)
- Copy operation takes time
Call/Pass-by-reference: parameter is placeholder to access argument
- Efficient for large data values (eg. objects) → no time-inefficient copy operation
- Takes up less memory
- Do it for efficiency sake, so copies are not created