Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a Prototype Constructor in C++

I am taking a quadratic expression, where y=ax^2 + bx + c with a,b,c are constants and x is a variable. Here is my class:

class quadratic {
public:
double evaluate(const double x);
void getCoefficients (double &A, double &B, double &C);
void setCoefficients (const double A, const double B, const double C);

private:
double a;
double b;
double c;
};

I am to create TWO constructors for the class so that the following is legal

quadratic y1 = quadratic(1.0, -5.0, 7.0);
quadratic y2 = quadratic(-3.0, -2.0, 10.0);
quadratic y3;

The default constructor should be set to zero while the parameters in the second constructor indicate initial values for the coefficients.

Here is how I believe I should do that:

quadratic()   //default values
{
double A, double B, double C = 0.0;
}

quadratic(double A, double B, double C)   //initial values
{
double A = double a;
double B = double b;
double C = double c;
}

However I'm not fully understanding how to set this up and would appreciate any gurus help in figuring this out.

like image 243
Zach Smith Avatar asked Sep 10 '10 11:09

Zach Smith


1 Answers

You should probably use the constructors' initializer list instead:

quadratic() : a(0), b(0), c(0)
{
}

quadratic(double A, double B, double C) : a(A), b(B), c(C)
{
}

The above uses a part of the C++ language to initialize member variables called an initializer list.


What you did for the constructor with parameters:

double A = double a;
double B = double b;
double C = double c;

First of all won't compile, but even if you simplify what you did to:

double A = a;
double B = b;
double C = c;

Then it is still won't compile because A, B, and C are already defined. When you put a type name followed by a variable name like the above, it will try to create a new variable.

So if we simplify again to:

A = a;
B = b;
C = c;

Then this is still wrong again but at least it will compile. It's wrong because you are setting the parameters to the value of the uninitialized class variables.

Instead you want:

a = A;
b = B;
c = C;

What you did for the constructor without parameters:

 double A, double B, double C = 0.0;

This won't compile. The right syntax to declare many variables in a single line is as follows:

 double A = 0, B = 0, C = 0;

But this is still not correct, it will simply create 3 new variables A, B, and C and initialize them to 0. What you really want is to set your member variables a,b, and c.

So you want:

a = b = c = 0;

like image 78
Brian R. Bondy Avatar answered Sep 18 '22 10:09

Brian R. Bondy