Can someone explain what each line does, coment on each line starting from prive
ID: 639730 • Letter: C
Question
Can someone explain what each line does, coment on each line starting from privet. thanks.
#include <iostream>
using namespace std;
class Hannah
{
private:
int h;
public:
Hannah(int);
void printCrap();
};
Hannah::Hannah(int num)
{
h=num;
}
void Hannah::printCrap()
{
cout << "h: " << h <<endl;
cout <<"this-> h: " << this->h <<endl;
cout << " (*this).h: " << (*this).h <<endl;
}
int main()
{
Hannah age(23);
age.printCrap();// calling print function
}
Explanation / Answer
#include <iostream>
using namespace std;
// creating class Hannah
// you can create Hannah objects as Hannah objH;
class Hannah
{
private:
// this is private section
// elements in this section can not be accessed directly using an object
// example if objH is the object of Hannah, then Hannah.h is not allowed
// if h is declared in public section, you can access h as Hannah.h
int h;
public:
// Hannah(int) is a parameterized constructor
// please note that this is just a prototype
// constructors are always created in public section
// constructorr function has same name as the class, and return nothing(not even void)
Hannah(int);
// printCrap() is a method which prints something crappy!!
void printCrap();
};
// Here is the definition of the constructor(prototype must be created in public section)
// before Hannah(int num) there is Hannah::
// which means the following method belongs to Hannah class
Hannah::Hannah(int num)
{
h=num;
// initializing h to num(Parameter)
}
// this is your printCrap function
// it returns void
// It belongs to Hannah class (That's why Hannah::)
// It takes no arguments(Parameters)
void Hannah::printCrap()
{
cout << "h: " << h <<endl; // printing value of h
cout <<"this-> h: " << this->h <<endl;
// this is another way of printing h
cout << " (*this).h: " << (*this).h <<endl;
// this is another way of printing h
}
// this is main function
int main()
{
Hannah age(23);
// creating Hannah object using an argument 23
// this creates an Hannah object and calls the constructor
// which initializes h of this object to 23
age.printCrap();// calling print function
// this prints value of h three times
}