Object Oriented Programming in C++
Object Oriented Programming in C++ CSCI 211 Lab 24 Lab Instructor: Yun Wang QUEENS COLLEGE
Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects".
It enables the organization of software design around data, or objects, rather than functions and logic.
Definitions
Class:
A user-defined data type that can be used in programs.
Analogy: A class can be thought of as a blueprint or frame for creating objects.
Object:
An instance of a class; the result of using a class template to create a structure in memory.
Class Declaration
Keyword 'class': Used to create a class.
Example Declaration:
class cookie {
public:
int numberofChocolateChip;
}; // Ends with a semicolon
Access Specifier -
public:Indicates that the members of the class are accessible from outside the class.
Variables declared in the class are called attributes.
Private Access Specifier:
Members declared as private are only accessible within the class itself, shielding their state from outside access.
Encapsulation:
A fundamental principle of OOP that controls access to the internal data of a class.
Maintains the integrity and consistency of an object's state, preventing unwanted interference.
Data Hiding:
This principle protects an object's internal state by preventing direct access to its private members.
Provides a clean interface for interacting with the class, reducing the likelihood of misuse.
Class Constructor
Definition: A special member function of a class that is called automatically when a new object of that class is created.
Characteristics:
Must have the same name as the class.
Default constructors do not take any arguments.
Constructors do not have a return type.
Typically must be placed in the public section of the class.
C++ generates a default constructor if none is specified by the developer.
Example Structure
Students.cpp Code Example:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
float grade;
public:
// Constructor
Student(string n, int a, float g) {
name = n;
age = a;
grade = g;
}
// Method to print student information
void printInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Grade: " << grade << endl;
}
// Method to check if the student is passing
bool isPassing() {
return grade >= 60.0;
}
};
int main() {
// Create an array of Student objects
Student students[3] = {
Student("Alice", 20, 85.5),
Student("Bob", 22, 45.8),
Student("Charlie", 19, 72.2)
};
// Print information for each student
for (int i = 0; i < 3; i++) {
cout << "Student " << i + 1 << " Information:" << endl;
students[i].printInfo();
cout << "Passing: " << (students[i].isPassing() ? "Yes" : "No") << endl;
}
return 0;
}
Object Creation Instructions:
To create an object based on the constructor:
ClassName ObjectName;
Practice Task
Create a C++ class representing a "BankAccount" with the following attributes:
balance: a double, initialized with an initial balance.
accountNumber: a string, initialized with an account number.
Implement functionalities within the
BankAccountclass:A constructor that initializes balance and accountNumber attributes.
A method
deposit(double amount)to allow depositing money.A method
withdraw(double amount)to withdraw money (only if the balance suffices).A method
getBalance()to return the current balance.
Advanced Practices
Demonstrating BankAccount Class:
In main program, perform the following operations:
Create a
BankAccountobject with a balance of $1000.0 and an account number (e.g., "ACCT12345").Deposit $500.0 into the account.
Attempt to withdraw $2000.0 from the account, ensuring it respects the balance.
Print the current balance after each operation.
Operator Overloading
Concept: Operator overloading in C++ allows custom definition of how operators (+, -, /, etc.) behave with user-defined data types.
Can be applied to both binary operators (which take two operands) and unary operators (which take one operand).
Common Operators that can be Overloaded:
Arithmetic Operators: +, -, *, /, %
Comparison Operators: ==, !=, <, >, <=, >=
Increment and Decrement Operators: ++, --
Assignment Operators: =, +=, -=, *=, /=
Stream Operators: <<, >>
Function Call Operator: ()
Note: The dot operator (.) cannot be overloaded.
Reference for C++ operators that can and cannot be overloaded is available online.
Example of Operator Overloading
Defining a Class Vector for 2D Vectors:
Overload the
+operator for vector addition.
**Steps for Overloading an Operator:
Choose the Operator to Overload.
Define the Class.
Declare the Operator Overload Function (using the required syntax).
Implement the Operator Overload Function.
Optionally use Friend Functions.
Test the Operator Overload.
// Example Pseudo Code for Vector Addition
class Vector {
// Data members for x, y
public:
// Implement operator+ for vector addition
};
Operators as Class Method
Implementation note: When defining operators as methods within classes, direct access is available to private members.
Operators such as
+and-can be marked asconstas they do not modify the current object (i.e., the object on which the method is invoked).Contrastingly, assignment operations require modifying the object and must not be
const.
Summary of Operator Overloading
Many operators may be overloaded for use in user-defined classes,
Including mathematical and logical operators.
Operator precedence rules are respected by the compiler.
Remember that not all operators can be overloaded, including the dot operator.
A comprehensive list of C++ operators and their overloadability can be found online.
Important Notes on Operator Overloading
Operators cannot be overloaded to act on primitive data types (e.g., the
+operator cannot be overloaded for adoubleandint).One of the operands must be of a user-defined class type to overload.
Overloading can occur with various combinations like
object + intordouble + object.
Overloading Techniques
Operators can be defined as functions or class methods.
If an operator is a class method, "this" denotes the left operand.
Assignment operators must be defined as methods, modifying the "this" object, hence cannot be marked as
const.
Practice Exercise: Fraction Class
Define a class
Fractionto represent fractions.Overload the
+,-,*, and/operators for basic arithmetic on fractions.Modify code to implement operators as class methods.