Section 5 Flashcards
MultiLevel Inheritance
Class derived from an already derived class
Create a multilivel inheritance class
class MyClass {
public:
void myFunction() {
cout «_space;“Some content in parent class.” ;
}
};
// Derived class (child)
class MyChild: public MyClass {
};
// Derived class (grandchild)
class MyGrandChild: public MyChild {
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
Multiple Inheritance
Class derived from more than one base classes
Give an example of multiple inheritance
class MyClass {
public:
void myFunction() {
cout «_space;“Some content in parent class.” ;
}
};
// Another base class
class MyOtherClass {
public:
void myOtherFunction() {
cout «_space;“Some content in another class.” ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
Create a derived class and a base class for an Employee as the base and Programmer as the Derived.
Employee should have a protected access specifier that Programmer can set and get
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout «_space;“Salary: “ «_space;myObj.getSalary() «_space;“\n”;
cout «_space;“Bonus: “ «_space;myObj.bonus «_space;“\n”;
return 0;
What is polymorphism?
Basically just overwrite a base classes method with your own shit
It means many forms.
When classes are related to each other by inheritance.
Inheritance lets us inherit attributes and methods and Polymorphism uses those methods to perform different tasks.
EXAMPLE:
Base class Animal has a method called animalSound().
Derived class of Animals could be pigs, cats, etc and they also have their own implementation of an animalsound.
Set and Animal base class
give it a method called animal sound.
Set a pig and dog derived class
Use polymorphism with the method of Animal for these
class Animal {
public:
void animalSound() {
cout «_space;“The animal makes a sound \n”;
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout «_space;“The pig says: wee wee \n”;
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout «_space;“The dog says: bow wow \n”;
}
};
What library do we need to manipulate files?
include <fstream></fstream>
What are the three classes that comprise fstream?
ofstream - create and write
ifstream - read files
fstream - combo of both, creates, reads and writes
Create and open a text file called filename.txt
Write something to the file
Close the file
include <iostream></iostream>
You can use either ofstream of fstream
#include <fstream>
using namespace std;</fstream>
int main() {
// Create and open a text file
ofstream MyFile(“filename.txt”);
// Write to the file
MyFile «_space;“Files can be tricky, but it is fun enough!”;
// Close the file
MyFile.close();
}
Read from a file and print it line by line
string myText;
// Read from the text file
ifstream MyReadFile(“filename.txt”);
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout «_space;myText;
}
// Close the file
MyReadFile.close();
How do you handle errors?
try - code to be tested for errors
throw - throws an exception when problem is detected. You can create a custom error
catch - Code to be executed if there’s an error in try block
Create a try box that has and a set and and if statement.
If the age is over 18 you are granted access, if not you should throw and exception and put the age as an argument.
If there is an error that was caught with ‘else’ you should report an access denied and print the age
try {
int age = 15;
if (age >= 18) {
cout «_space;“Access granted - you are old enough.”;
} else {
throw (age);
}
}
catch (int myNum) {
cout «_space;“Access denied - You must be at least 18 years old.\n”;
cout «_space;“Age is: “ «_space;myNum;
}
Create an error for if your age is under 18.
The error should be 505 and the catch keyword should print the error number
try {
int age = 15;
if (age >= 18) {
cout «_space;“Access granted - you are old enough.”;
} else {
throw 505;
}
}
catch (int myNum) {
cout «_space;“Access denied - You must be at least 18 years old.\n”;
cout «_space;“Error number: “ «_space;myNum;
}
Create a try catch and throw. The catch should be able to catch any type of exception.
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout «_space;“Access granted - you are old enough.”;
} else {
throw 505;
}
}
catch (…) {
cout «_space;“Access denied - You must be at least 18 years old.\n”;
}
return 0;
}
You’ll notice that the type isn’t there like the last example. So this will catch any data type provided, whether string, int, etc.
When you specify an asset specifier for your derived class, like below, what does it do?
class Developer: public Employee
This specifies how you want to treat the members of Employee for you class.
Public keeps everything the same when transferring them over
Private makes public and protected members private
protected makes public members protected.
Which library allows you to work with time?
ctime
Declare a variable named timestamp to store time values in.
Get the current time in seconds and store it in your variable
Convert this to be human readable
// Get the timestamp for the current date and time
time_t timestamp;
time(×tamp);
// Display the date and time represented by the timestamp
cout «_space;ctime(×tamp);
What’s the difference between timestamps and datetime structures?
Timestamps - A moment in time as a single number which is easier for the computer to do calculations
Datetime Structures - Different components of the date and time as members. Easier to specify dates
What are the date time structures members?
tm_sec - The seconds within a minute
tm_min - The minutes within an hour
tm_hour - The hour within a day (from 0 to 23)
tm_mday - The day of the month
tm_mon - The month (from 0 to 11 starting with January)
tm_year - The number of years since 1900
tm_wday - The weekday (from 0 to 6 starting with Sunday)
tm_yday - The day of the year (from 0 to 365 with 0 being January 1)
tm_isdst - Positive when daylight saving time is in effect, zero when not in effect and negative when unknown
What are data structures?
Used to organize data
An array is a structure
Data structures are a part of c++ STL
What is C++ STL
Standard Template Library
consists of data structures and algorithms to effectively store and manipulate data
data structures store data and algorithms are used to solve different problems, often by searching through and manipulating data structures
What are the most common data structures?
How do you access these?
include vector
Vector - Stores elements, can change size, is indexed
List - Sequentially stored, add and remove at both ends, not indexed
Stack - LIFO stored in Last in first out. Only add and removed from top. No index
Queue - FIFO, add and removed from front, not indexed
Deque - stored in double ended queue, can add and remove from both ends. Indexed.
Set - Unique elements, not indexed
Map - key and value. Not indexed
Create a vector with four different car types. Print each item out.
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};</string>
// Print vector elements
for (string car : cars) {
cout «_space;car «_space;“\n”;
}
What are the key components of STL
Containers - Data structures that provide a way to store data, like vectors and lists
Iterators - Objects used to access elements of a data structure
algorithms - sort(), find(), functions that perform operations on data structures through iterators
What do vectors and arrays have in common
What makes them different
data structures used to store multiple elements of the same data type
Arrays can’t be resized but vectors can
Create a vector of 4 cars
print the first element
print the second element
access the first element and then the last with a function
// Create a vector called cars that will store strings
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};</string>
// Get the first element
cout «_space;cars[0]; // Outputs Volvo
// Get the second element
cout «_space;cars[1]; // Outputs BMW
cout «_space;cars.front();
cout «_space;car.back();
above you can also use
cout «_space;car.at(2);
at is used more because it lets you know an error occured
Let’s pretend you have a vector called cars
Change the name of the first element
cars[0] = “Opel”;
cars.at(0) = “Opel”;
Add an element to the end of a vector
cars.push_back(“Tesla”)
Remove an element from the end of a vector
cars.pop_back()
Show how many elements a vector has
cout «_space;cars.size()
Show if a vector is empty or not
1 - it is empy
0 - it is not empty
cars.empty();
Loop through a vector
EASY:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};</string>
for (string car : cars) {
cout «_space;car «_space;“\n”;
}
HARD:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};</string>
for (int i = 0; i < cars.size(); i++) {
cout «_space;cars[i] «_space;“\n”;