Date: March 26, 2013
Time: 14:10-16:00
Open book; turn off computer & mobile phone
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Size of a string
#include <iostream>
#include <cstring>
class CMessage
{
public:
char str[20];
CMessage(char* s)
{ strcpy(str, s); }
};
int main()
{
CMessage city("Vatican");
std::cout << sizeof(city) << std::endl;
std::cout << strlen(city.str) << std::endl;
return 0;
}
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Size of an object
#include <iostream>
#include <cstring>
class CMessage
{
public:
char* str;
CMessage(char* s)
{
str = new char[strlen(s) + 1];
strcpy(str, s);
}
~CMessage()
{
delete str;
str = NULL;
}
};
int main()
{
CMessage city("Vatican");
std::cout << sizeof(city) << std::endl;
// Assume that you are running this program on a 32-bit operating system
std::cout << strlen(city.str) << std::endl;
return 0;
}
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Access Control
#include <iostream>
class CBox // Class definition at global scope
{
private:
int m_Length; // Length of a box in inches
int m_Width; // Width of a box in inches
int m_Height; // Height of a box in inches
CBox(int lv, int wv, int hv) // Constructor
{
m_Length = lv;
m_Width = wv;
m_Height = hv;
}
public:
int Volume()
{
return m_Length * m_Width * m_Height;
}
};
int main()
{
CBox box1(2, 3, 4); // Declare box1 of type CBox
std::cout << box1.Volume() << std::endl;
return 0;
}