I have a silly question:
I have a class and in one of its methods I have to do some calculations and I need to declare some variables that are useful to do this. For example:
class Percettrone {
public:
Percettrone(double NL);
void fit(double X, double y);
}
.
.
.
void Percettrone::fit(double X, double y)
{
double delta[50][50];
double conteggio=0;
//calculations
}
Is it correct? Or is it better to declare when I create the class? Moreover I have to call this method lots of time during my programme
If those variables are affecting the object instance and identifying its state, then you must declare them in the class as attributes. On the other hand, if they're just helper variables in the function, and you don't need to use them anywhere else, then make them local inside the function as you did in the example.
Related
I have a method that needs to calculate results for two variables in a object, so I am using pointers to return the results. The problem occurs because the object properties are private and can only be accessed through a getter method. The code I have looks like this:
Class myObject;
//Some other operations on myObject
double firstPram = myObject.getFirstDouble();
double secondPram = myObject.getSecondDouble();
someFunction(&firstPram, &secondPram);
myObject.setFirstDouble(firstPram);
myObject.setSecondDouble(secondPram);
This works but doesn't seem like the most elegant or efficient solution. Doing something like
someFunction(&myObject.getFirstDouble(), &myObject.getSecondDouble());
doesn't work and I get why. I just want to know if there is a way to access a varible through a method with a pointer.
It looks like someFunction should be a member of Class, because it reads and writes private variable. It can still reuse the standalone someFunction. E.g.:
void someFunction(double*, double*);
class Class {
double first_, second_;
public:
void someFunction() {
::someFunction(&first_, &second_);
}
};
The problem is "do you really want that an external object edits directly a private variable?". Probably not: you declared it private, so you should edit that through public method in that class. A good way is to pass the entire object to someFunction that edit the variables with getter and setter methods.
The second snippet will work if you change function getFirstDouble to return reference:
double& getFirstDouble()
of course it will break encapsulation even more than your current getters and setters.
How about having the function someFunction() within your class?
Let that function manipulate the object's variables.
So by calling myObject.someFunction(), you can do your necessary functionality. Also you don't have to expose the variables by getters and setters too.
I have this function:
void fraction::init()
{
cout<<"enter the values for the numerator and denominator\n";
cin>>num;
cin>>denom;
}
and I want these two numbers to be used in another function that manipulate them.
how do I take them to this other function?
NOTE:both functions are of the same classs.
Simply define them as members of the class:
class fraction {
private:
int num;
int denom;
public:
void init(); // has access to num and denom
void otherMethod(); // also has access to num and denom
};
You should also not rely on init() being called to initialize the variables with a default value, and you should also not rely on the various default initializations provides by C++, see Default variable value.
Instead, add a constructor which sets default values for the variables to make sure that the variables have reasonable values after an object of the class has been created. Then, you can still call init() to set whatever values you want (and probably you should rename init() to something like readValues() to reflect what the method really does).
It depends on how you will be using those functions. Since both belong to the same class, you can make num and denom (private) members of the class. But you can also use references if those values come from outside the class. This will work regardless of the functions belonging to the same class or not:
class fraction
{
public:
void init(int& num, int& denom) const;
void otherFunction(int num, int denom);
}
void fraction::init(int& num, int& denom) const
{
cout<<"enter the values for the numerator and denominator\n";
cin>>num;
cin>>denom;
}
// Define otherFunction() appropriately
Then use those functions in another piece of code:
// ...
int aNum, aDenom;
fraction fr;
fr.init(aNum, aDenom);
fr.otherFunction(aNum, aDenom);
// ...
Either make them members of the class, as so many suggest, or you could try passing them when needed. If you want their values to reflect changes, pass them by reference.
datatype function1(int *a, int *b)
And then when you call them from init() function,
function1(&num, &denom)
Hope this helps
I am trying to do this C++ tutorial. I am a beginner in C++ programming. I don't get why they use setValue and getValue in class Class1 and not setClass1. In the other tutorial they use setA and getA in the class class Class1. Here are the codes:
class Class1 {
int i;
public:
void setValue( int value ) { i = value; }
int getValue() { return i; }
};
the second code is:
class A{
int ia;
public:// accessor method because they are used to access a private date member
void setA ( const int a);
int getA ()const;
int getA ();
};
Please help...
The names are arbitrary, you can use any function names you wish (subject to language rules, of course).
However, although you can use xyzzy() and plugh() as getter and setter, it's not really a good idea.
You should use something that indicates the intent of the call, such as getTemperature() or setVelocity(). And these don't even have to map one-to-one to internal fields since encapsulation means the internal details should not be exposed.
By that, I mean you may have a getTemperatureC() for returning the temperature in Celsius even though the internal field is stored as Kelvins:
double getTemperatureC(void) { return kelvins - 273.15; }
void setTemperatureC(double t) { kelvins = t + 273.15; }
(or a getter/setter may use arbitrarily complex calculations).
Using getA() for a class A may well cause you trouble when you create class B to inherit from A but this is outside the scope of the language. But it's good programming practice to follow the guideline above (functions should indicate intent rather than internals).
I was confused on why they use the same name in get and set with the class name, and different get and set name on the other class. Will the set and get names affect the code?
The answer is No.
getter and setter are usually called accessor and mutators in a class. They are just member functions named according to some convention, easy for people who read the code to understand the purpose of those functions, so it is like common sense to name those member function starting with get if you try to access the member variables and starting with set if you try to change some member variables. The names can be any valid identifier.
So setValue or setA are just identifiers for those member functions. It will not affect the code.
Meanwhile, different class can have the same named getter or setters since those function names are in different class scope.
I am currently learning C++ and having some problems understanding on how to give values to the constructor. Got my exercise working but am not sure which way is smartest/best.
Way nr. 1
class Vector2d{
public:
Vector2d(double x, double y):x(x),
y(y)
{
}
and way nr.2
class Vector2d{
public:
void set_values (double,double);
Vector2d()
{
}
void Vector2d::set_values (double a, double b) {
x = a;
y = b;
}
Found both ways by reading some tutorials and both ways are working. I guess the first one is more efficient as I donĀ“t have to write a new void, but I am not exactly sure what
:x(x),
y(y)
is doing/meaning.
Thanks a lot in advance!
In C++ doing it by saying
:x(x),
y(y)
You will actually save instructions when it is compiled. The compiler will actually initialize those variables directly inline when space is made for the class.
So I would say that way is better.
I am not exactly sure what [code...] is doing/meaning.
They are initializing your member variables.
It's probably confusing because your constructor parameters were given the same names. Consider this equivalent:
Vector2d(double x_param, double y_param)
: x(x_param) // initialize member variable "x"
, y(y_param) // initialize member variable "y"
{
}
It's reasonable for your class to have both this constructor, and the set_values function to change the values after construction.
Constructor with parameter is created to initialize the member attributes of the class (your 1st solution) and it is different from default constructor (with no parameters - constructor in your 2nd solution).
In your second solution, you are using a setter (a member function to set the values of member attributes) which we can call anytime we need to set the values but with the constructor with parameters (1st solution), we can only set the values for the first time when we create an object to that class.
For example;
when we create the object;
Vector2d vec2d(2.3, 4.5);
it will set the values of x and y to 2.3 and 4.5 respectively but what will we do if we need to set the values again in the program? We will then use setter function like;
vec2d.set_values(5.0, 7.8);
so in short, we only use what we need according to our scenario. If we don't want to set the values again then constructor with parameters (your 1st solution) is the best.
We do the following
:x(x),
y(y)
to assign the value of x and y coming through parameters in constructor to the class members x and y. It is the same as;
class Vector2d{
public:
Vector2d(double x, double y)
{
//"this" pointer is used to differentiate the variables
this->x = x;
this->y = y;
}
}
or for the simplicity I would suggest to use different names if you don't know about this pointer yet;
class Vector2d{
public:
Vector2d(double a, double b)
{
x = a;
y = b;
}
}
with #1 you are instructing the program to initialize x,y by calling their constructor
with #2 you are calling operator= to overwrite the value of x,y by: the value obatained by calling the two constructors: x.operator=(double(right_value))
doesn't differ much since the type involved is "double", would be much different with some complex classes i guess
First way is calling the constructor to initialize members; second way is calling member function to change the value of member variables by assigning, since you only define default constructor, initially members are initialized with default value, then if you call the set_values function, they are reassigned inside that function body. In the current example, they will have the same effect. But it is usually better to initialize member variables at the constructor's initializer list. Your second way looks like a setter function. You cannot use the second way to initialize class member variables since it is not static.
It is preferrable to use the first way if you are constructing an object.
Using the initializer list, the members are created and initialized only once, with the given value.
If you will use separate function to initialize your object, than between constructor call and initialization, your object will be in unitialized state.
The only case you need it - when really know what are you doing.
And also initializing in constructor is faster. When you write
my_class()
: field_(value)
{
}
your field initialized by copying value into it. In other case it initialized, when copied, which is overhead.
Suppose I have a class as follows:
class Solution {
public:
std::vector<double> x;
}
Suppose I have a function as follows:
void function(Solution& sol) {
// do some calculations on the solution vector
}
Under some circumstances, I will want function to perform calculations directly using the vector x. However, under some circumstances I will want to perform calculations using another vector that is produced by a mapping of the vector x.
Give these possible circumstances, it makes sense to introduce an additional member to the class Solution, but in the first circumstance this additional member will simply refer to x, and in the second circumstance this additional member will itself be another std::vector that is determined by a mapping of some form.
So, ideally I could add a ctor to Solution that creates/defines a member named y either as a std::vector or as merely a reference to x. Then, my function could simply operate directly using y.
How might I do this?
You can define your function as:
void function(std::vector<double>& x)
And pass different vectors to it, depending on circumstances
Edit Using references in ctors
class Solution
{
std::vector<double> x;
std::vector<double>& y;
public:
Solution(std::vector<double>& _y) : y(_y) { }
Solution() : y(x) { }
void function() { /* do work on y*/ }
};
This way your function always operates on the same reference, but you can control what data this reference refers to. Note that x and y are now private -- this ensures that these members are only used locally via function() method.