1/67
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
What are classes for? What would C++ look like without classes?
Classes are for grouping together stored data and the functions that operate on them in a single new data type.
Without classes, you would only be able to work with variables and functions separately.
For example:
Which is the object and which is the class in the following example?
Rectangle rect;
Rectangle is the class
rect is the object of that class
What is an object?
Write a statement to give an example of an object.
An instance of a class.
Rectangle rect1;
Identify the key features of the following example:
class Student {
private:
int grade;
public:
void setGrade(int newGrade);
int getGrade();
};class Student {
private: // access specifier
int grade;
public: // access specifier
// member functions
void setGrade(int newGrade)
int getGrade();
}; // a class definition always requires a semicolon after the closing braceWhy can’t you do this?
class Student {
public:
int grade;
}
int main() {
Student s;
s.grade = 90;
}You technically can do this. The disadvantage is that the rest of your program now has unrestricted access to the variable, so you could even do assignment statements like:
s.grade = -500
which makes no sense.
But if a variable is private, we can control its modification through functions.
What does the protected access specifier mean?
It means it is only accessible to derived classes (has to do with inheritance).
What is the dot operator for?
The dot operator is for accessing public members.
What is the scope resolution operator for?
::
The scope resolution operator is used for defining a function that belongs to a particular class.
Example:
int Rectangle::area()
What good habit is the following program demonstrating?
#include <iostream>
using namespace std;
class Rectangle {
private:
int width;
int height;
public:
void setValues(int, int);
int area() {
return width * height;
}
};
void Rectangle::setValues(int x, int y) {
width = x;
height = y;
}It is demonstrating the good habit of declaring a function inside the class, and defining it outside:
#include <iostream>
using namespace std;
class Rectangle {
private:
int width;
int height;
public:
void setValues(int, int); // declared here
int area() {
return width * height;
}
};
void Rectangle::setValues(int x, int y) { // defined here
width = x;
height = y;
}What is the main difference between using a class and a struct? Don’t they both allow us to contain functions and variables?
The difference is their default member access.
In a class, variables are private by default, while in a struct, variables are public by default.
Example:
class Example {
int x; // private by default
};
struct Example {
int x; // public by default
};When we say “A member function in C++ is implicitly inline”, what do we really mean?
When you define a function inside a class, it is treated as an inline function. This means that instead of jumping to another place in memory to execute the function, it just copy and pastes the function’s code directly into the block where it needs to run.
This also optimizes the program.
Write a complete C++ program that:
Creates a Rectangle class
Stores width and height as private ints
Has a public setValues function that assigns the width and height
Has a public area() function that returns area
In main() create a Rectangle object, give it a width of 5 and height of 8, and print its area.
#include <iostream>
class Rectangle {
private:
int width;
int height;
public:
void setValues(int, int);
int area();
};
void Rectangle::setValues(int x, int y) {
width = x;
height = y;
}
int Rectangle::area() {
return width * height;
}
int main() {
Rectangle rect1;
rect1.setValues(5,8);
std::cout << rect1.area() << std::endl;
}Write a complete C++ program that:
Creates a Student class.
Stores a student's name and grade privately.
Provides public functions to set the name and grade.
Provides a public function that displays both.
Create two different Student objects in main() and give them different information.
#include <iostream>
#include <string>
class Student {
private:
double grade;
std::string name;
public:
void setName(std::string);
void setGrade(double grade);
void displayNameAndGrade();
};
void Student::setName(std::string name1) {
name = name1;
}
void Student::setGrade(double givengrade) {
grade = givengrade;
}
void Student::displayNameAndGrade() {
std::cout << "Grade: " << grade << "\n" << "name: " << name << std::endl;
}
int main() {
Student student;
Student student2;
student.setName("Arthur");
student.setGrade(89.5);
student2.setName("Sofia");
student2.setName(90.3);
student.displayNameAndGrade();
student2.displayNameAndGrade();
return 0;
}When you create objects in C++, does each object receive its own data?
Yes!
What is a constructor?
A special member function used to initialize an object of a class. It has no return type.
What is the defining feature of a constructor?
It has no return type.
Identify the constructor in the following example:
class Rectangle {
private:
int width;
int height;
public:
Rectangle(int, int);
int area();
};
Rectangle::Rectangle(int a, int b) {
width = a;
height = b;
}
int Rectangle::area() {
width * height;
}The constructor is Rectangle(int, int);
In main, initialize a Rectangle object called rect, with a width of 3 and 4.
class Rectangle {
private:
int width;
int height;
public:
Rectangle(int, int);
int area();
};
Rectangle::Rectangle(int a, int b) {
width = a;
height = b;
}
int Rectangle::area() {
width * height;
}int main() {
Rectangle rect(3,4);
}Is this allowed?
class Rectangle {
private:
int width;
int height;
public:
Rectangle();
Rectangle(int, int);
int area();
};Yes, overloaded constructors are allowed.
What distinguishes one overloaded function from another?
We can overload a constructor by creating another with the same name but different parameter lists. This means either: parameters of different types or a different number of parameters.
What is a default constructor?
A default constructor is a constructor that can be called with 0 arguments.
For example:
Rectangle();is a default constructor.
Therefore this works:
Rectangle rect;We call it the default constructor because it is the ordinary constructor that is automatically generated for you by C++ when you don’t create one yourself.
Once you’ve declared your own constructor, does C++ still generate a default, no argument constructor for you?
No. Once you’ve defined your own constructor, C++ will no longer generate a default one for you. If you would like both a custom constructor, and a default constructor, you will have to define both:
Example:
Rectangle();Rectangle(int, int);Create a Book class containing:
A private string title.
A private int pages.
A constructor accepting a title and number of pages.
A member function called displayBook() that prints both.
Create two different Book objects using different constructor arguments and display them.
class Book {
private:
std::string title;
int pages;
public:
Book(std::string, int);
void displayBook();
};
Book::Book(std::string t, int p) {
title = t;
pages = p;
}
void Book::displayBook() {
std::cout << "title:" << title << "\n" << "pages:" << pages << std::endl;
}
int main() {
Book book1("Book1", 242);
Book book2("Book2", 300);
displayBook(book1);
displayBook(book2);
return 0;
}Create a Laptop class containing private:
std::string brand;
double price;
Give it two constructors:
Laptop();
Laptop(std::string, double);
The default constructor should assign "Unknown" and 0.
The second constructor should use the values supplied by the programmer.
Then create:
Laptop laptop1;
Laptop laptop2("Microsoft", 1299.99);
and display both objects.
class Laptop {
private:
std::string brand;
double price;
public:
Laptop();
Laptop(std::string, double);
};
Laptop::Laptop() {
brand = "Unknown";
price = 0;
}
Laptop::Laptop(std::string type, double p) {
brand = type;
price = p;
}
int main() {
Laptop laptop1; // for a default constructor, do not write Laptop laptop1(), because that will make it interpret laptop1() as a method call.
Laptop laptop2("Microsoft", 1299.99);
return 0;
}What are the three different ways of initializing things with constructors?
Functional/Direct Initialization: Circle circle1(10.0);
Assignment-looking Initialization: Circle circle2 = 20.0;
Direct List Initialization: Circle circle3{30.0}; or Circle circle4 = 40.0;
Why is Direct List initialization helpful?
Let’s say you have an object called: Laptop laptop1;
You may sometimes make the mistake of doing Laptop laptop1(); when using direct/functional initialization. This is wrong because it gets interpreted as a method call.
You can however, write Laptop laptop1{}; in direct list initialization, which completely avoids this trap.
What is another way to initialize this exact same constructor body:
Laptop::Laptop(std::string type, double p) {
brand = type;
price = p;
}We can also initialize it like this:
Laptop::Laptop(std::string type, double p)
:brand(type), price(p) {}Fill in the blanks here:
How can we initialize the value of base with r, given that base is an object of type Cylinder?
class Circle {
private:
double radius;
public:
Circle(double r)
:radius(r)
{
}
double area() {
return radius * radius * 3.14;
}
};
class Cylinder {
private:
Circle base;
double height;
public:
Cylinder(double r, double h)
// initialize base to r and height to h public:
Cylinder(double r, double h)
:base(r), height(h) {}We must use direct-list initialization whenever we have objects nested within objects.
We know that:
int number = 10;
int* ptr = &number;So how can we create a pointer to the following Rectangle object?
Rectangle obj(3,4);Rectangle obj(3,4);
Rectangle* ptr = &obj;Assuming we have the following pointer, how can we access a member through this pointer? Specifically, how can we calculate the area() on the underlying rectangle? Write the statement to do this.
Rectangle obj(3, 4);
Rectangle* ptr = &obj;Rectangle obj(3, 4);
Rectangle* ptr = &obj;
ptr->area(); // this calls area() on the underlying rectangle
(*ptr).area(); // this also does the exact same thing (is equivalent to the statement above)Given the following pointer to a Rectangle, create a dynamic object with new for this pointer.
Afterwards, calculate its area.
Rectangle* bar;Rectangle* bar;
bar = new Rectangle(5,6);
bar->area();
delete bar; // never forget to delete when you manually create an objectHow can we create an array of rectangles called baz?
The first rectangle in the array should be 2 × 5, and the second should be 3 × 6.
Rectangle* baz = new Rectangle[2] {
{2,5},
{3,6}
};Create a Movie class containing a private std::string title and double rating.
Give it a constructor accepting both values.
Create two Movie objects using { } uniform initialization and add a function that displays their information.
class Movie {
private:
std::string title;
double rating;
public:
Movie(std::string, double);
void displayMovie();
};
Movie::Movie(std::string t, double r) {
title = t;
rating = r;
}
void Movie::displayMovie() {
std::cout << title << "\n" << rating << std::endl;
}
int main() {
Movie movie1{"Star Wars", 4.5};
movie1.displayMovie();
return 0;
}Create a Book object and a pointer that points to it. Display the Book's information twice:
once using the object and .
once using the pointer and ->
Note: Book has two parameters, title, and movie rating as a double.
Book myBook{"book1", 300};
Book* bookptr = &myBook;
myBook.displayBook();
bookptr->displayBook();
(*bookptr).displayBook(); // bonusCreate a Student class containing:
std::string name;
double grade;
Write a constructor that initializes both members using a member initializer list, not assignments inside the constructor body.
Add a display() function and test the class in main().
class Student {
private:
std::string name;
double grade;
public:
void display();
Student(std::string, double);
};
Student::Student(std::string n, double g)
: name(n), grade(g)
{
}
void Student::display() {
std::cout << name << "\n" << grade << std::endl;
}
int main() {
Student sofia{"Sofia", 99.9};
display(sofia);
}Given:
class Rectangle {
private:
int width;
int height;
public:
Rectangle(int w, int h)
: width(w), height(h) {}
int area() {
return width * height;
}
};Write only the main() function that:
Dynamically creates a Rectangle with dimensions 7 × 9 using new.
Stores its address in a Rectangle* pointer called rectPtr.
Get the area using ->.
Release the dynamically allocated object when finished.
int main() {
Rectangle* rectPtr;
rectPtr = new Rectangle(7,9);
rectPtr->area();
delete rectPtr;
}Using the same Rectangle class above, write only the main() function that:
Dynamically creates an array containing three Rectangle objects using new[].
Give them dimensions:
2 × 5
4 × 6
3 × 8
Store the resulting pointer in:
Rectangle* rectangles;
Print the area of each rectangle.
Rectangle* rectangles = new Rectangle[3] {
{2,5},
{4,6},
{3,8}
};
std::cout << rectangles[0].area();
std:: cout << rectangles[1].area();
std::cout << rectangles[2].area();
delete rectangles;Can you include visibility modifiers in a struct?
Yes, you can.
Example:
struct Example {
private:
int x;
public:
void setX(int n) {
x = n;
}
};What is a union? What distinguishes unions from other class types?
Another special class type. Except the major difference is that it can only hold one active, non-static data member at a time. This is because the members share storage.
In the following example, what happens when you try to print wholeNumber?
Explain why this happens.
Union Data {
int wholeNumber;
double decimal;
};
// somewhere in main
Data value;
value.wholeNumber = 25;
value.decimal = 4.5;
std::cout << value.wholeNumber << std::endl;You should NEVER try to print wholeNumber. This is because it creates undefined behavior.
In a Union, there can only be a single active member at a time. At first, our active member was value.wholeNumber, because we assigned 25 to it. But then afterwards, we did value.decimal = 4.5, so now decimal was the active member.
Because Union members have overlapping storage, when one member is active, the other member cannot be active at the same time. So when you try to print an inactive member, you get undefined behavior.
However, this does not mean that wholeNumber itself is now undefined, or that it is equal to the same value as decimal. It just means that reading wholeNumber while decimal is the active member will cause problems. This is mainly because we overwrite the previous value’s location in memory.
Why do we need overloaded operators? Use this as an example to explain:
class CVector {
public:
int x;
int y;
CVector(int a, int b)
: x(a), y(b) {}
};
int main() {
CVector first(3,1);
CVector second(1,2);
return 0;
}We need overloaded operators to define a certain operation for a custom type we’ve created. For example, in the following code, if we were to do first + second, we need a way of knowing what this means; And so, we can define a method that specifically describes its behavior.
Describe what is happening in the following example, specifically in the code marked by the comment:
#include <iostream>
class CVector {
public:
int x;
int y;
CVector()
: x(0), y(0)
{
}
CVector(int a, int b)
: x(a), y(b)
{
}
CVector operator+(const CVector& other);
};
// THIS PART
CVector CVector::operator+(const CVector& other) {
CVector temp;
temp.x = x + other.x;
temp.y = y + other.y;
return temp;
}
int main() {
CVector foo{3, 1};
CVector bar{1, 2};
CVector result;
result = foo + bar;
std::cout << result.x << ", " << result.y << std::endl;
return 0;
}// const prevents this function from modifying the object through other. For example, you probably don't want to unexpectedly modify bar when doing foo + bar
// other refers to the right hand CVector
// and CVector& means it holds a CVector address
CVector CVector::operator+(const CVector& other) {
CVector temp;
temp.x = x + other.x; // this is the same as temp.x = foo.x + bar.x = 3 + 1 = 4
temp.y = y + other.y; // this is hte same as temp.y = food.y + bar.y = 1 + 2 = 3
// so when we return temp, we return the resulting CVector, where:
// result.x = 4 and result.y = 3
return temp;
}
Explain why our function only takes one argument, when addition clearly involves 2 objects:
CVector CVector::operator+(const CVector& other) {
CVector temp;
temp.x = x + other.x;
temp.y = y + other.y;
return temp;
}Well this is because foo is an object that calls the operation on bar:
foo operator+ (bar)
so there is no need for 2 separate parameters. You have one object calling a method on another.
Describe what is happening in the following example, specifically in the code marked by the comment:
#include <iostream>
class CVector {
public:
int x;
int y;
CVector()
: x(0), y(0)
{
}
CVector(int a, int b)
: x(a), y(b)
{
}
};
// THIS PART
CVector operator+(const CVector& lhs,
const CVector& rhs)
{
CVector temp;
temp.x = lhs.x + rhs.x;
temp.y = lhs.y + rhs.y;
return temp;
}
int main() {
CVector foo{3, 1};
CVector bar{1, 2};
CVector result;
result = foo + bar;
std::cout << result.x << ", "
<< result.y << std::endl;
return 0;
}// when implemented as a non-member function (a function not inside a class), it requires to parameters
CVector operator+(const CVector& lhs,
const CVector& rhs)
{
CVector temp;
temp.x = lhs.x + rhs.x;
temp.y = lhs.y + rhs.y;
return temp;
}
// in the same way, this method corresponds to a call shaped like: operator+(foo, bar)How come the member function and the non-member function take a different number of parameters? Is this just a stylistic choice? To have one function take 2 and the other only take 1?
// THE MEMBER FUNCTION
CVector CVector::operator+(const CVector& other) {
CVector temp;
temp.x = x + other.x;
temp.y = y + other.y;
return temp;
}
// THE NON-MEMBER FUNCTION
CVector operator+(const CVector& lhs,
const CVector& rhs)
{
CVector temp;
temp.x = lhs.x + rhs.x;
temp.y = lhs.y + rhs.y;
return temp;
}It is not a stylistic choice for the second function to take two arguments. In fact, the reason the first function only has a single argument is because it is part of the class. Since it is a member/class function, it hides the left operand because the left operand is already the object that called the member function.
When it is not a member/class function, we have no way of knowing that the first operand is an object of the correct type, so we have to pass in two arguments.
Create a struct called Book containing:
std::string title;
int pages;
Do not write public:.
Give the struct a display() member function.
In main(), create a Book, give its members values directly using . and display it.
struct Book {
std::string title;
int pages;
void display() {
std::cout << title << "\n" << pages << std::endl;
}
};
int main() {
Book myBook;
myBook.pages = 3;
myBook.title = "Hello";
myBook.display();
}Question 2: Member operator+
You're given:
class Score {
public:
int points;
Score() : points(0) {}
Score(int p) : points(p) {}
Score operator+(const Score&);
};Do not rewrite the class.
Write:
The definition of operator+ outside the class.
A main() creating scores containing 40 and 25.
Add them using:
score1 + score2
Print the resulting points.
Score Score::operator+ (const Score& other) {
Score temp;
temp.points = points + other.points;
return temp;
}
int main() {
Score score1(40);
Score score2(25);
Score result = score1 + score2;
std::cout << result.points << std::endl; // do not do: std::cout << score1 + score2 << std::endl; because we haven't yet taught std::cout how to print objects
return 0;
}You're given:
class Number {
public:
int value;
Number() : value(0) {}
Number(int v) : value(v) {}
};Do not rewrite the class.
Write a non-member overload of operator+ that adds two Number objects and returns a new Number.
Then create:
Number first{15};
Number second{25};
and use your overload to produce and print 40.
Number operator+ (const Number& num1, const Number& num2) {
Number temp;
temp.value = num1.value + num2.value;
return temp;
}
int main() {
Number first{40};
Number second{25};
Number result = operator+(first, second); // you could also do result = first + second here!!! despite the two arguments
std::cout << result.value << std::endl;
return 0;
}How does a member function know which object is calling it?
It knows because of the this keyword. This is because this is a pointer containing the address of the object on which the member function was called.
In the following example, what does this point to?
sofia.display()this points to sofia.
Our function is display(), and the current object, the object on which the member function was called on is sofia.
Since this is a pointer containing the address of the current object, this points to sofia.
In the following example, what is this equivalent to?
class Student {
public:
void showAddress() {
std::cout << this << std::endl;
}
};
int main() {
Student sofia;
std::cout << &sofia << std::endl;
}this is equivalent to &sofia
We know this because this holds the address of the current object. The current object is sofia, so it holds the address &sofia.
Why do we sometimes write this→
What is the most common use case for this?
The most common use case for this is when we give the parameter name the same name as the data member. Using this→ helps us distinguish between the two.
Example:
class Student {
private:
std::string name;
public:
void setName(std::string name) {
this->name = name;
}
};
// this -> name means the name belonging to the current object
// name is the parameter, nameIn the following example, describe what each of the following mean:
Dummy&, Dummy* ptr and ¶m
bool Dummy::isitme(Dummy& param) {
if(¶m == this) {
return true;
}
else {
return false;
}
}Dummy& = means a reference to some Dummy. Here the & means reference, not address. All this is saying is that param is another name (an alias) for the object that gets passed in.
Dummy* ptr = means a pointer to a Dummy. Here, ptr actually stores an address.
¶m = because param is just another name for the object that gets passed in, ¶m means give me the address of the object referred to by param. If param = a, then ¶m = &a.
What will be the output of the following code when we do:
Dummy a;a.isitme(a);bool Dummy::isitme(Dummy& param) {
if(¶m == this) {
return true;
}
else {
return false;
}
}param becomes an alias for a.
this is the address of the current object, and the current object is a.
therefore the comparison is:
¶m == this
&a == &a
returns true
Since param is an alias to the a we just passed in, asking for the address of param is the same as asking for the address of a.
And because this is the address of the current object, and the current object is a, this is the same as &a.
What will be the output of the following code when we do:
Dummy a;
Dummy b;a.isitme(b);bool Dummy::isitme(Dummy& param) {
if(¶m == this) {
return true;
}
else {
return false;
}
}param becomes an alias for b.
¶m == this
&b == &a
returns false
Since param is an alias to the b we just passed in, asking for the address of param is the same as asking for the address of b.
And because this is the address of the current object, and the current object is a, this is the same as &a.
The address of b is not equal to the address of a, so it returns false.
Dummy a;
Dummy* b = &a;b->isitme(a);bool Dummy::isitme(Dummy& param) {
if(¶m == this) {
return true;
}
else {
return false;
}
}param becomes an alias for a.
¶m == this
&a == &a
returns true
Since param is an alias to the a we just passed in, asking for the address of param is the same as asking for the address of a.
And because this is the address of the current object, and the current object is a, this is the same as &a. Don’t get confused here: b is not actually an object, it is a pointer, and because of this, when we do b→isitme(a) we are actually saying a.isitme(a).
The address of a is equal to the address of a, so it returns true.
Describe what it means to have static int n here.
Then describe what the output will be after each line.
using namespace std;
class Dummy {
public:
static int n;
Dummy() {n++};
};
int Dummy::n=0;
int main() {
Dummy a;
Dummy b[5];
cout << a.n << "\n" << "\n"
Dummy *c = new Dummy;
cout << Dummy::n << "\n";
delete c;
return 0;
}When you only have:
public:
int n;then when you do:
Dummy a;
Dummy b;You would have a separate n value for each object.
a --- n
b --- nWhereas when you have:
public:
static int n;Now n is associated with the Dummy class itself, not individual objects.
Dummy class -- nTHE OUTPUT:
using namespace std;
class Dummy {
public:
static int n; // means the Dummy class shares an integer called n
Dummy() {n++}; // every time the constructor runs, increment n
};
int Dummy::n=0; // With static members, we need to provide its actual definition outside of the class; This means we initialize the starting value of n to 0. We use :: notation because the n value belongs to the class, not to any individual objects.
int main() {
Dummy a; // Constructs one Dummy, then the constructor runs, incrementing n to n=1
Dummy b[5]; // Constructs 5 more Dummies, now n++ happens 5 more times, n = 6
cout << a.n << "\n" << endl; // Prints the current value of n by accessing it through the a Dummy object. Prints 6.
Dummy *c = new Dummy; // Creates a pointer to a Dummy and constructs a new Dummy to point to using the new keyword. n = 7.
cout << Dummy::n << "\n"; // Prints the current value of n by accessing it through the class. Prints 7
delete c; // Must delete the object allocated with new.
return 0;
}Explain why, in the previous example, it is okay for us to access the value of n by doing both:
a.nAND
Dummy::nIt doesn’t matter how we access it because n is static, meaning it belongs to the entire class. Whether you ask for the value of n through a specific Dummy object, or through the class, you get the same result.
Although, accessing static members through the class is more conventional.
What do you notice about the following example below:
class Calculator {
public:
static int add(int a, int b) {
return a+b;
}
};
int main() {
std::cout << Calculator::add(5,3);
return 0;
}That we do not need to create a calculator object. Because it is static, it belongs to the class level, so we can access it directly using the class name.
When you have a static member function, such as the one seen in Calculator, do you have a this pointer?
In the example from earlier, because it is a static member function, there is no particular Calculator object calling add().
Therefore, static member functions do not have a this pointer.
What happens if you declare an object as being const?
const MyClass object(10);It means that after construction, you cannot modify the object through that const object.
So doing something like:
object.x = 20; // Would not be allowedWill this code run? Why or why not?
Let’s say you have:
class Student {
private:
double grade;
public:
Student(double g)
:grade(g) {}
double getGrade() {
return grade;
}
};Then somewhere in main:
const Student sofia{99.99};
std::cout << sofia.getGrade() << std::endl;This code will not run. The reason being that we created a const object.
When you create a const object, you need to promise to the compiler never to modify it. We can do this by changing double getGrade() to double getGrade() const:
class Student {
private:
double grade;
public:
Student(double g)
:grade(g) {}
double getGrade() const { // changed
return grade;
}
};const is a promise that you will never modify the object through its non static data members.
Is this a correct C++ statement?
const Student sofia{99.99};
std::cout << sofia.getGrade(); << std::endl;No, it is not. Be careful with the semicolons. Semicolons end a statement, so if you add one here early, it causes problems.
What is the type of this when it comes to a const function?
this is a pointer to the current const object.
In the example with Student from earlier, this would be a pointer to a const Student:
const Student * (read from right to left as “Pointer to a const student”)
Question 1: this
You're given a class containing:
class Student {
private:
std::string name;
public:
Student(std::string name);
void display();
};Write the constructor definition outside the class using:
this->
to distinguish the object's name from the parameter named name.
Then define display() and test it in main().
Student::Student(std::string name) {
this->name = name;
}
void Student::display() {
std::cout << name << std::endl;
}
int main() {
Student sofia("Sofia");
sofia.display();
return 0;
}Question 2: You're given:
class Player {
public:
static int count;
Player() {
count++;
}
};Do not rewrite the class.
Write the necessary code outside the class to initialize count to zero.
Then, in main():
Create three Player objects.
Print the shared count using the class name rather than one of the objects
int Player::count = 0;
int main() {
Player player1;
Player player2;
Player player3;
std::cout << Player::count << std::endl;
std::cout << player1.count << std::endl;
return 0;
}Create a Book class containing a private:
std::string title
Give it:
a constructor that initializes title
a getTitle() function that can legally be called on a const Book
Then create:
const Book myBook{"C++"};
and print its title.
class Book {
private:
std::string title;
public:
std::string getTitle() const;
};
int main() {
const Book myBook{"C++"};
std::cout << myBook.getTitle();
return 0;
}Given:
class Box {
public:
bool sameObject(Box& other);
};Define sameObject() so that it returns true when other refers to the same object that called the function.
bool Box::sameObject(Box& other) {
if(this == Box& other) {
return true;
} else {
return false;
}
}