#include<iostream>
//this code will handle request from main to access private values
//can work without the constructor
class Pass_it
{
private:
int var_1 = 120;
int var_2 = 98;
public:
Pass_it()
{
var_1, var_2;
}
void print_it()
{
std::cout<<var_1<<" "<<var_2;
}
};
int main()
{
Pass_it pass_it;
pass_it.print_it();
return 0;
}
I provide a constructor or not and the program executes the same
Yes you provided a constructor, however that constructor isn't actually doing anything and is therefore unnecessary. You used the assignment to initialize the variables on lines 8 and 9, not the constructor.
I'll answer my own question there (below - public method retrieving private values). I think I'm trying to force the constructor issue because I am studying them. I'll have to wait for the need to develop would be a better strategy.
ok, how would I then use a public method to retrieve private values? That's were I am stuck.
You are doing that just fine (printing them). But you don't have a ctr to set any member variables, that is the purpose of them.
1 2 3 4 5 6 7 8
public:
Pass_it(constint var1Arg, constint var2Arg)
: //colon introduces initializer list
var_1 (var1Arg), // make sure to set all members variables here
var_2 (var2Arg) // in the same order as listed in the private section
{
//do validation here
}
If you mean retrieving the variables as in returning them, just use a get function, or a function with parameters as references, or return a std::tuple.
In C++11 is the same as using an initializer list with those values. But the ctr I had shown is better, because one can set any values via the arguments.
Generically what circumstances would I be most prone to use constructors.
For two reasons:
1 to initialize all the member variables
2 to validate the member variables
But what do we do if we are writing a program where exceptions cannot be used? First challenge that assumption; there are many anti-exceptions myths around. We know of only a few good reasons:
We are on a system so small that the exception support would eat up most of our 2K or memory.
We are in a hard-real-time system and we don’t have tools that guarantee us that an exception is handled within the required time.
We are in a system with tons of legacy code using lots of pointers in difficult-to-understand ways (in particular without a recognizable ownership strategy) so that exceptions could cause leaks.
We get fired if we challenge our manager’s ancient wisdom.