C++ Class Constructors and Methods - c++

I have a take home test that it work a large percentage of my grade. These 3 questions are on it and they are worth half the test. I was wondering if someone could kindly review my quiz and make sure they are correct for me. I’m a worrier and I want to make sure they are correct. Thank you in advance!
Implement the constructor for the class called "SimpleMath". The constructor takes two integer parameters; "var1" and "var2". The constructor is to store the value that was passed into "var1" into the private integer member variable "m_value1" and the value that was passed into "var2" into the private integer member variable "m_value2"
class SimpleMath
{
public:
SimpleMath(int var1, int var2) : m_value1(var1), m_value2(var2) {};
int getVar1() const
{
return m_value1;
}
int getVar2() const
{
return m_value2;
}
private:
int m_value1;
int m_value2;
};
Implement the "Multiply" method for the "SimpleMath" class. This method does not require any parameters and returns an integer value. This method should multiply the values stored in the classes private integer member variables "m_value1" and "m_value2" the resulting value is returned. Assume that "m_value1" and "m_value2" were loaded inside the classes constructor.
class SimpleMath
{
public:
SimpleMath(int var1, int var2);
int Mutiply= m_value1* m_value2;
private:
int m_value1;
int m_value2;
};
Write a class definition called "SimpleMath" that has a constructor that takes two integers "var1" and "var2". It has four public methods that take no parameters and return an integer value; "Add","Subract","Divide" and "Multiply". The class has two private member variables of type integer; "m_value1" and "m_value2".
class SimpleMath
{
SimpleMath(int var1, int var2);
public:
int Add;
int Subract;
int Divide;
int Multiply;
private:
int m_value1;
int m_value2;
};

Am I to assume you have no prior programming experience?
At any rate, the first part looks ok. What the : denotes is the initializer list. It can, and is, correctly used to initialize a class's members.
Second part, you got it dead wrong I am afraid.
First of, you've not implemented the method Multiply() there, you've just declared a variable.
Instead do this:
int Multiply()
{
int sum = m_value1 * m_value2;
return sum;
}
For brevity's sake, you can also do this:
int Multiply()
{
return m_value1 * m_value2;
}
Does the same thing.
Also note that the answer from question 1 has not carried over to question 2, ie the constructor is incomplete. It won't compile.
As for question 3, it's just question 2 all over again, except you've also got to implemented the three remaining arithmetic functions. Suffice it to say, I am sure you can figure it out.

Related

C++ Comparing two structures to show what are the difference

I have two structs like this
struct Activity {
int id;
string Description;
int parameter1;
int parameter2;
int parameter3;
int parameter4;
etc...
}
Activity A1;
A1.id=0;
A1.parameter1=50;
Activity A2;
A2.id=0;
A2.parameter1=55;
I would like to compare them, to show what members are different ?
In this case something like :
paameter1 is different...
Thanks
The best solution to do this may be to write public method inside the structure which will compare themselves with structure passed through parameter.
This will look like this
struct Activity {
int id;
string Description;
int parameter1;
int parameter2;
int parameter3;
int parameter4;
etc...
public:
bool compare(const Activity& param)
{
//...compare structs here like:
if (id != param.id)
//write something
//etc...
//at the end you can also return bool that indicates that structs are equal or not
return true;
}
}
This will obviously work only with two the same classes unless you write more comparison methods, but it may be difficult to compare two different structures.
There is also other way to compare two variables (including structs). For this a memcmp() function can be used, but it will not tell you directly, which fields are different.
Edited according to what #Tony_D said.

C++ Rectangle Class clarification regarding syntax

I'll try to make this as concise as possible and while I understand that these questions can be considered "basic" I have already looked at websites such as cplusplus.com and yolinux tutorials but i need somebody to explain this to me like I have just had a major head trauma..
1)
class Rectangle {
private:
int lineNumber; // LineNumber of the ACSIL Tool
float valueMax; // value of the higher limit of the rectangle
float valueMin; // value of the lower limit of the rectangle
public:
Rectangle(SCStudyInterfaceRef sc, int lineNumber, float valueMax, float valueMin);
int getLineNumber();
float getValueMax();
float getValueMin();
};
So int linenumber, valueMax and ValueMin are declared private members and thus are only accessible by members of the same class, thats fine. But what about the part that follows the "public:" ?
a) Is Rectangle(SCStudyInterfaceRef sc, int lineNumber, float valueMax, float valueMin); a function that is being overloaded? and if yes are int getLineNumber() etc part of that function or seperate members of the public part of the class?
2)
Rectangle::Rectangle(SCStudyInterfaceRef sc, int lineNumber0, float value1, float value2) {
lineNumber = lineNumber0;
int value2_greater_than_value1 = sc.FormattedEvaluate(value2, sc.BaseGraphValueFormat, GREATER_OPERATOR, value1, sc.BaseGraphValueFormat);
if (value2_greater_than_value1 == 1) {
valueMax = value2;
valueMin = value1;
} else {
valueMax = value1;
valueMin = value2;
}
}
int Rectangle::getLineNumber() {
return lineNumber;
}
float Rectangle::getValueMax() {
return valueMax;
}
float Rectangle::getValueMin() {
return valueMin;
}
a) I'm pretty sure that the functions defined inside the public part of the rectangle class are being "defined" here, or something along those lines.
b) I am really confused about what is happening here on the Rectangle::Rectangle(SCStudyInterfaceRef sc, int linenumber0, float value1, float value2) part. I understand the logic of what is happening within the function itself but i am confused about the paramters being input within the " ( ) " and how exactly this relates to what happenes inside the class public part. This really is the most important question that needs answering.
I have tried to be as concise and onpoint as possible, would appreciate some help in understanding this syntax.
Question 1
It's a constructor with 4 parameters.
int getLineNumber();
float getValueMax();
float getValueMin();
are all member functions in the class.
Question 2
The constructor defined earlier is called with 4 parameters. If no other constructor is defined then you'll have to instantiate the class with exactly 4 parameters, i.e:
Rectangle *rect = new Rectangle(sc, 100, 1.2, 6.8);
or simply:
Rectangle rect(sc, 100, 1.2, 6.8);
These parameteres are then used to "set the object in an initial state".
The member functions are used to get various values in their current (or final or only) state.
Rectangle::Rectangle is the class constructor. It is called whenever a Rectangle object is created. Read about constructors to understand better.
The constructor is setting initial values for the valueMax and valueMin member variables. It uses the parameters passed to the constructor to do this. Read about function parameters to understand better.
1) a: If no ctor function is declared, then the compiler writes a ctor for the class. But when a ctor is provided by the class no default ctor is written by the class and hence no overloading is taking place. Now if you go on and define one more ctor, may be because you want the object to be constructed in some other way, then you will have an overloaded ctor. In your case no overloading is taking place.
int getLineNumber() is just another member of the class.
2)
a: You are correct.
b: The parameters put inside "( )" are arguments list and if this function is called somewhere, then this list is type-matched and then function is called(in case of overloading). Now if you write a statement like:
Rectangle x(a, b, c, d);
then it means that your sc=a, lineNumber0=b, value1=c, value2=d for this function call.

Calling virtual method of a derived class causes segfaults

I'm trying to make a chess program, but I want to be able to implement different AIs in it. Thus I made a abstract AIgeneric class and the derived class AIrandom off of AIgeneric. Then in my chessAI interface, I create a list of the the AIs, and try to call their getNextMove function and run into a segfault. The code is as below:
class AIgeneric {
public:
virtual int getNextMove(int*, const int &) = 0;
}
class AIrandom : public AIgeneric {
public:
AIrandom();
virtual int getNextMove(int*, const int &);
}
class chessAI {
public:
chessAI();
~chessAI();
void setAI();
int getNextMove(int*, const int &);
private:
vector<AIgeneric*> AIlist;
vector<string> names;
int selectedAI;
};
chessAI::chessAI () {
AIrandom randomAI;
AIlist.push_back(&randomAI);
names.push_back("Random AI");
selectedAI = -1;
}
int chessAI::getNextMove(int * board, const int & color) {
return AIlist[selectedAI]->getNextMove(board, color); //segfault on this line
}
It'd be great if anyone could help me on this problem!
Edit: I do set selectedAI to 0 before calling getNextMove.
In this code:
chessAI::chessAI () {
AIrandom randomAI;
AIlist.push_back(&randomAI);
names.push_back("Random AI");
selectedAI = -1;
}
You store a pointer to a local variable into your vector. After the constructor returns that pointer is no longer valid.
Remember that all local variables are stored on the stack, and the stack is reused in other functions. So when you use the pointer in the vector, it now points to some other functions memory and not the one object you declared.
This can be solved in three ways:
Allocate the object on the heap:
AIlist.push_back(new AIRandom);
Not using pointers at all.
Use smart pointers, such as std::unique_ptr.
You call selectedAI = -1; and then AIlist[selectedAI]->.... What do you expect AIlist[-1] to be, other than undefined behavior?
I expect this is because AIlist[selectedAI] is out of bounds. You can confirm this by replacing it with AIlist.at(selectedAI). Keep in mind that this index is -1 immediately after the constructor...

How to insert function into data structure?

In a data-structure, how do you insert a function?
struct Student_info {
std::string name;
double midterm, final;
unsigned int& counter;
std::vector<double> homework;
double overall = grade(students[counter]);
};
always get this type of error:-
a. "variable" was not declared in this code.
b. "Student_info::counter" cannot appear in a constant-expression.
c. an array reference cannot appear in a constant-expression.
d. a function call cannot appear in a constant-expression
edit:-
oopps, i mean student_info contain in a vector, wait, why that's info needed anyway... Dx
oh, and btw, this is from Accelerated C++, a book obviously, and I'm trying to answer one of its exercise, then I need to know this part, not found any on the book Dx
the question is 4-6. Rewrite the Student_info structure to calculate the grades immediately and store only the final grade.
You can NOT dynamically insert a function into a structure.
You can declare a structure that has a method()
struct Student_info
{
void doDomethingToStudent()
{
// Manipulate the object here.
}
// STUFF
};
Also you can not initialize member like above.
double overall = grade(students[counter]);
Here you need to create constructor that will initialize members.
struct Student_info
{
Student_info(std::string& studentName, unsigned int& externalCounter)
: name(studentName)
, midterm(0)
, final(0)
, counter(externalCounter)
, homework()
// It is not clear if overall is a normal memeber
// Or a static member of the class
, overall(grade(students[counter]))
{}
// STUFF
};
int main()
{
unsigned int counter = 0;
Student_info bob("Bob", counter);
}

Class data default initialization

I have following code:
#include <iostream>
using namespace std;
class Base
{
private:
int i;
char ch;
public:
void showdata()
{
cout<<"Int:"<<i<<endl;
cout<<"Char:"<<ch<<endl;
}
//int pub_data ;
} ;
int main()
{
Base ob;
ob.showdata() ;
//cout<<"Public Data:"<<ob.pub_data<<endl;
return 0;
}
This program compiles and runs fine. The output shows that i is initialized with 0 and ch is initialized with '\0'.
If you notice i have commented out 2 statements in this program. First the declaration of public data pub_data and second the line inside main printing this public data.
Now here the problem is, if i uncomment these two lines, the data members of class i.e. i, ch, pub_data do not seem to be initialized and when printed, they display junk values.
So my question is what difference public data makes here?
I'm using g++ 3.4.6
Neither int's nor char's are automatically initialized to 0. The fact that it happened is just luck.
You need to add a constructor that does the initialization:
Base() : i(0), ch(0) {}
None. You're just getting "lucky". Fundamental types remain uninitialized, so your i and ch, as the program stands, could very well not always be 0.
It just so happens adding that public member "messes it up". To correct your class, initialize the members in the initialization list of the constructor:
class Base
{
private:
int i;
char ch;
public:
Base(void) :
i(0), ch(0) //, pub_data(0)
{}
void showdata()
{
cout<<"Int:"<<i<<endl;
cout<<"Char:"<<ch<<endl;
}
//int pub_data ;
} ;
Now when a Base gets constructed i, ch, and (when uncommented) pub_data will be properly initialized to meaningful values.
As opposed to Java or C#, where memory allocated for a newly created objects ALWAYS set to zero, this NOT happends in C++. There are several rules that describe when object initialization is guaranteed to take place and when it isn't.
Consider folowing example:
class Base
{
private:
int i;
char ch;
std::string str;
public:
Base()
: i(0) //built-in fields remains unitialized. We should initialize it manually
, ch('\0') //another built-in field
//, str() //this call is redundant due automatic default constructors calls for all user-defined types
{}
void showdata()
{
cout<<"Int:"<<i<<endl; //valid only after manual initialization
cout<<"Char:"<<ch<<endl; //valid only after manual initialization
cout<<"String:"<<str<<endl; //always valid
}
//int pub_data ;
} ;
You should remember, that ALL buit-in fields you should initialized manually in class constructor.
P.S. The fact, that in the first case your code works - is pure accident.
What has been answered already is correct, but to make sure your values are zero-initialized you can also simply declare your object as
Base ob(); // notice the parentheses here
or
Base ob{}; // this compiles only on c++11
For more details, check out this insightful answer:
https://stackoverflow.com/a/620402/3073460