C++ - constructor for nested non-pointer class - c++

There is non-pointer (body) nested class in outer class.I need to call its constructor from outer class constructor after some calculations.How to do?
class nested
{
int value;
nested(int x) {value=x;};
nested() {value=0;};
};
class outer:
{
nested n;
nested *pn;
outer(int x);
};
outer::outer(int x1)
{
x = x1;
y = x + 1 *x*x;//some long calculations needed for nested
pn = new nested(y); //this is trivial
n = nested(y); //??? how to initialize non-pointer class?????
}

One solution would be to calculate y and store it as a member variable. That way you can calculate and cache it before initializing anything that depends on it.
class outer
{
public:
outer(int x)
, y(CalculateY(x))
, n(y)
, pn(new nested(y))
{}
private:
int CalculateY(int x); // this can be static
int y;
nested n;
nested *pn;
};
Note
int y must be declared before anything that relies on it since member variables are initialized in the order they're declared in.

Related

How to initialize variable dynamically in class declaration, and being not constant

How to initialize variable(s) dynamically i.e. being not as constant, in class declaration which will be invoked/used without need of object instantiation such as a constructor for member function call immediately gets returned in a function ?
There must, side by side of that variable(s) in that class, be a constant member.
enum Value :int { NO,LOW,MED,HIGH };
template<Value V> class valuation {
public:
valuation(const ints) : pos(s) {};
valuation(int a, int b, int c) : j(a), k(b), l(c) {};
value() {
if (!V)
return (j+k+l) * pos;
}
private:
const int pos;
int j,k,l;
};
int a_function(int s) {
return valuation<NO>(s).value(); // no need object at all
}
int main() {
// somehow in run-time j, k, l has been given 1,2,3, or other valid values
int v = a_function(7) // e.g.
}
Thanks in advance
I think you want to declare your value method -- or at least a version of it -- as a static member. This will allow you to call the method without instantiating an object from your class.

How to create from nested lambda expression Functor classes

I have started to learn about lambda expressions and nested lambda expressions:
auto Suma=[](int x)->function<int(int)>
{
return [x](int y)
{
return x+y;
};
};
auto Mult=[](function<int(int)>&f, int z)
{
return f(z)*2;
};
I would like to create 3 Functor classes (for better understanding how it works), it should be 3 classes Sum, Inner and Mult.
.h:
class Suma
{
public:
int operator()(int x);
};
class Inner
{
Suma function;
public:
Inner(int x);
int operator()(int k);
};
class Mult
{
public:
int operator()(Suma function,int z);
};
.cpp:
int Suma::operator()(int x)
{
return x;
}
Inner::Inner(int x)
{
function.operator()(x);
}
int Inner::operator()(int k)
{
return function.operator()+k;
}
int Mult::operator()(Suma function,int z)
{
return (function.operator())*(2);
}
The main issue I face is when trying to include the function from one related class to another. I dont fully understand the main idea of how it is connected through classes. Could please advice me how should it work.
Your classes do not reflect the structure of the lambdas.
The inner lambda returns a function with adds its paramter to the capture.
So your Inner class shall not depend on Suma, and be defined as follows:
// definition in .h
class Inner
{
int myx;
public:
Inner(int x); // this represents the capture of the lambda
int operator()(int k); // this is the function of adding k to the catpture
};
// implementation in .cpp
Inner::Inner(int x)
{
myx = x;
}
int Inner::operator()(int k)
{
return myx + k;
}
The Suma shall then return an Inner with an x set:
// definition in .h
class Suma
{
public:
Inner operator()(int x);
};
// implementation in .cpp
Inner Suma::operator()(int x)
{
return Inner(x);
};
With your lambdas, when you evaluate Suma(3), you'll obtain a function that takes an integer and adds 3 to it. If you evaluate Suma(3)(2) you therefore get 5.
With the classes emulating the lambdas, you would then do the same:
Suma f; // that is an object, like "auto suma"
cout << f(3)(2) <<endl; // f(3) is in fact an object Inner(3) wich is then exectued with argument 2.
Here you have an online demo.
You could even be closer to the structure of your lambdas by having Inner be a nested class of Suma.
Now looking at the Mult class, it appears that the first argument is not a Suma object, but the result of an invocation to Suma (i.e. return type of its operator()) . So it's an Inner. Hence, you can complete the code as follows:
// definition in .h
class Mult {
public:
int operator()(Inner& function, int z);
};
// implementation in .cpp
int Mult::operator()(Inner& function, int z)
{
return (function(z))*(2); // funtion(z) means function.operator()(z)
}
By the way, as you see above, you don't need to explicitely call operator(): just provide the arguments between parenthesis.

Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript - C++

I've this error when I try to save a number into my vector...
Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript
The code is:
class Elemento{
private:
int Nodo;
public:
Elemento(){};
~Elemento(){};
void SetNumero(int x) { Nodo = x; };
int GetNumero() { return Nodo; };
};
class MagicSquare{
private:
int N;
int Possibili_N;
int Magic_Constant;
vector<Elemento> Square(int Possibili_N);
public:
MagicSquare() { };
~MagicSquare() { };
void Set_N(int x) { N = x; };
void Set_PossibiliN(int x) { Possibili_N = x; };
void Set_MagicConstant(int x) { Magic_Constant = x; };
. . .
void SetSquare(int i, int x) { Square[i].SetNumero(x); }; // got error here
int GetSquare(int i) { return Square[i].GetNumero(); }; // got error here
};
I've got error whenever I use Square[i].method()...
I call a method that pass the index in the Square and the value to put in Elemento->Nodo, but I've to use a public method to access to private Nodo. The same with the GET. I want to get the value for displaying it.
You seem to have declared Square as a function, not a variable.
Instead, declare vector<Elemento> Square; and initialize it in the constructor.
You declared Square as a function, not a variable. So Square[i] is not valid.
Change
vector<Elemento> Square(int Possibili_N);
to
vector<Elemento> Square;
or call it using
Square(i)
if it is actually a function.
If you change it to a variable, you need to be sure to initialize it properly, preferably in the constructor.
Your line vector<Elemento> Square(int Possibili_N); is know as C++ most vexing parse.
Instead of declaring a member variable, as intended, you are declaring a function taking an int and returning a vector.
Instead, setup the member vector (and all other member variables) in the constructor initialization list:
class MagicSquare{
private:
int N;
int Possibili_N;
int Magic_Constant;
vector<Elemento> Square;
public:
MagicSquare( int n, int p, int m ) :
N( n ),
Possibili_N( p ),
Magic_Constant( m ),
Square( p ) {
}
...

What does explicitly initializing a member mean?

In the following code
class someClassB;
class someClassA
{
public:
someClassA(int x, int y);
private:
someClassB* B;
};
class someClassB
{
public:
someClassB(int x, int y);
private:
int x;
int y;
someClassA A;
};
someClassA::someClassA(int i, int j)
{
B->x = i;
B->y = j;
}
someClassB::someClassB(int i, int j)
{
x = i;
y = j;
A = new someClassA(i, j);
}
why do I get an error saying 'Constructor for 'someClassB' must explicitly initialize the member 'A' which does not have a default constructor'?
Am I not initializing 'A' in someClassB's constructor?
someClassA does not have a default constructor. Currently, someClassB needs to default initialize it, resulting in the compilation error you quote. .You need to explicitly initialize the someClassA data member using one of its available constructors. For example,
someClassB::someClassB(int i, int j) : x(i), y(j), A(i, j)
{
}
Here, x and y are also initialized in the constructor initialization list, as opposed to default initialized and then assigned values to, as in your code.
Also note that, in general, this makes no sense in C++:
A = new someClassA(i, j);
new returns a pointer.
Given that you are using A with new, I suspect you meant to declare it as a pointer:
someClassA* A;
If not, then you need to initialize it in someClassB's initializer list.
someClassA::someClassA(int i, int j)
{
B->x = i;
B->y = j;
}
create a new instance of class someClassB as B is a pointer and you didn't allocated memory for this.
A = new someClassA(i, j);
A is not a pointer this is an instance of someClassA

Creating 2-dimensional vector in class C++

I need to create a vector of vectors full of integers. However, I continuously get the errors:
error: expected identifier before numeric constant
error: expected ',' or '...' before numeric constant
using namespace std;
class Grid {
public:
Grid();
void display_grid();
void output_grid();
private:
vector<int> row(5, 0);
vector<vector<int> > puzzle(9, row);
int rows_;
int columns_;
};
You cannot initialize the member variables at the point where you declare them. Use an initialization list in the constructor for that:
Grid::Grid()
: row(5,0), puzzle(9, row),
rows_(5), columns_(9)
{
}
C++ class definitions are limited in that you cannot initialise members in-line where you declare them. It's a shame, but it's being fixed to some extent in C++0x.
Anyway, you can still provide constructor parameters with the ctor-initializer syntax. You may not have seen it before, but:
struct T {
T() : x(42) {
// ...
}
int x;
};
is how you initialise a member, when you might have previously tried (and failed) with int x = 42;.
So:
class Grid {
public:
Grid();
void display_grid();
void output_grid();
private:
vector<int> row;
vector<vector<int> > puzzle;
int rows_;
int columns_;
};
Grid::Grid()
: row(5, 0)
, puzzle(9, row)
{
// ...
};
Hope that helps.
You can't initialize a member in a class declaration unless it's const static, because in C++ no code is being run/generated when you are declaring a class. You'll have to initialize them in your constructor.
You should initialize members in the class constructor, not the declaration. The following doesn't seem to be right in any way:
vector<int> row(5, 0);
vector<vector<int> > puzzle(9, row);
If row and puzzle are functions - the parameters should be types. If they're member variables - initialize them in the class constructor.
You cannot initialize mutable members as a part of class definition itself. Instead do assign it in in the constructor.
// ....
Grid()
{
row.resize(5,0) ;
puzzle.resize(9,row) ;
}
private:
vector<int> row;
vector<vector<int> > puzzle ;
// ..