Reputation: 1
So I'm a total noob at C++, I decided to learn C++ and skipped directly to the Object-oriented programming. I'm coding a class called KineticEnergy
that has a constructor with the parameters x
and y
which is assigned to the variables mass
and velocity
.
I have a class method called result()
which calculates the Kinetic Energy using its formula. I want to call the parameters from my constructor within the formula but I have no idea what I'm exactly doing here (bad english, don't know how to explain). I am getting errors like "[Error] x
was not declared in this scope". Here is the code I written:
#include <iostream>
#include <cmath>
using namespace std;
class KineticEnergy
{
public:
double mass;
double velocity;
KineticEnergy(double x, double y) {
mass = x;
velocity = y;
}
double result()
{
return (1/2) * (x * (pow(y, 2)));
} // What am I gonna do here for this to work?
};
int main()
{
double a = 12.1;
double b = 6.4;
KineticEnergy ke(a, b);
cout << ke.result();
return 0;
}
Upvotes: 0
Views: 1502
Reputation: 40
try this
#include <iostream>
#include <cmath>
using namespace std;
class KineticEnergy
{
public:
double mass;
double velocity;
KineticEnergy(double x, double y) {
mass = x;
velocity = y;
}
double result()
{
return 0.5 * (mass * pow(velocity, 2));
}
};
int main()
{
double a = 12.1;
double b = 6.4;
double Result;
KineticEnergy ke(a, b);
Result = ke.result();
cout << Result;
}
x and y were declared in your constructor, therefore only known by your constructor. you cannot use them outside of it. however, mass and velocity are known variables of your class and can be used anywhere as long as they are public.
in your main you give mass and velocity of your ke
object values, that's why you can call any method of your class that uses these variables after(again, as long as they're public)
Upvotes: 0
Reputation: 57
Parameters of the parameterized constructor are not member variables. That's why you are storing param values in member variables inside of the parameterized constructor. So that, you should use member variables inside of the result() function.
Upvotes: 0
Reputation: 190
It is not necessary. your constructor parameters is saved in "mass" and "velocity" as class members.
double result()
{
return (1./2.) * (mass * (pow(velocity , 2.)));
}
Upvotes: 4