Initialising reference in constructor C++ - c++

I don't think is a duplicate question. There are similar ones but they're not helping me solve my problem.
According to this, the following is valid in C++:
class c {
public:
int& i;
};
However, when I do this, I get the following error:
error: uninitialized reference member 'c::i'
How can I initialise successfully do i=0on construction?
Many thanks.

There is no such thing as an "empty reference". You have to provide a reference at object initialization. Put it in the constructor's base initializer list:
class c
{
public:
c(int & a) : i(a) { }
int & i;
};
An alternative would be i(*new int), but that'd be terrible.
Edit: To maybe answer your question, you probably just want i to be a member object, not a reference, so just say int i;, and write the constructor either as c() : i(0) {} or as c(int a = 0) : i(a) { }.

A reference must be initialised to
refer to something.
int a;
class c {
public:
int& i;
c() : i (a) {};
};

Apart from the sweet syntax, a key feature of references is that you are pretty sure that it always point to a value (No NULL value).
When designing an API, it forces user to not send you NULL.
When consuming an API, you know without reading the doc that NULL is not an option here.

References have to be initialized upon creation. Thus you have to initialize it when the class is created. Also you have to provide some legal object to reference.
You have to use the initializer in your constructor:
class c {
public:
c(const int& other) : i(other) {}
int& i;
};

Reference should be initialised either by passing data to constructor or allocate memory from heap if you want to initialize in default constructor.
class Test
{
private:
int& val;
std::set<int>& _set;
public:
Test() : val (*(new int())),
_set(*(new std::set<int>())) { }
Test(int &a, std::set<int>& sett) : val(a), _set(sett) { }
};
int main()
{
cout << "Hello World!" << endl;
Test obj;
int a; std::set<int> sett;
Test obj1(a, sett);
return 0;
}
Thanks

template<class T>
class AVLNode {
private:
T & data;
public:
AVLNode(T & newData) {
data = newData;
}
};

Related

How to return a class instance on the heap, when the relevant ctor is private?

Suppose I have this struct
struct MyStruct {
static MyStruct Create(int x) {
return { x*2, x>3 };
}
MyStruct(const MyStruct& c) = delete; // no copy c'tor
private:
MyStruct(int a_, bool b_) : a(a_), b(b_) {} // private c'tor -- can't use new
const int a;
const bool b;
};
Edit: I deleted the copy constructor. This is simplified example of some classes I have in my codebase where they don't have copy c'tors.
I can get an instance on the stack like so:
int main() {
auto foo = MyStruct::Create(2);
return 0;
}
But suppose I need a pointer instead (or unique_ptr is fine), and I can't change the implementation of MyStruct, how can I do that?
You could wrap MyStruct in another class, which has a MyStruct member. Here's a minimal version of that:
class Wrapper {
public:
MyStruct ms;
Wrapper(int x) : ms(MyStruct::Create(x)) { }
};
which you can use like so:
int main() {
MyStruct::Create(2);
std::make_unique<Wrapper>(2);
}
This code will not trigger any copies nor moves - because of copy elision (see: What are copy elision and return value optimization?).
You can then add any other constructors and methods you like to such a wrapper, possibly forwarding some of the method calls to the ms member. Some might choose to make ms protected or private.
Is this what you're looking for?
auto baz = std::make_unique<MyStruct>( MyStruct::Create(2) ); // unique pointer
A comment rather than an answer, to avoid confusion for future readers.
I can get an instance on the stack like so:
int main() {
auto foo = MyStruct::Create(2);
return 0;
}
Note that this is only true as of C++17 and guaranteed copy elision, whereas the program is ill-formed is C++14, as even if the copy may be elided, the initialization of foo is copy-initialization from a temporary (in C++17: the temporary is never materialized).
One more way to do it:
struct ChildStruct : public MyStruct {
ChildStruct(int x) : MyStruct(MyStruct::Create(x))
{}
};
int main() {
MyStruct *foo1 = new ChildStruct(2);
return 0;
}
C style solution. I am not sure that this is not UB, but for simple struct with 2 integer fields it should work.
int main() {
auto foo = MyStruct::Create(2);
MyStruct *p = (MyStruct*)malloc(sizeof(MyStruct));
memcpy(p, &foo, sizeof(MyStruct));
//...
free(p);
return 0;
}

My lambda does not correctly convert the captured 'this' during copy construction

I've narrowed down my problem to exactly this
#include <iostream>
#include <functional>
struct Foo {
std::function<Foo*()> lambda;
Foo()
:lambda([this](){return this;})
{}
};
int main(){
Foo a;
Foo b = a;
std::cout << &a << " " << a.lambda() << std::endl;
std::cout << &b << " " << b.lambda() << std::endl;
}
where the output is
0x7ffd9128b8a0 0x7ffd9128b8a0
0x7ffd9128b880 0x7ffd9128b8a0
I originally expected that this would always point to the instance that owned the lambda. However I forgot about copy construction. In this case the lambda captures this and then it is fixed and no matter how many times the lambda is copied it points to the original value of this.
Is there a way fix this so that lambda always has a reference to it's owning object this even under copy construction of the owning object.
Sounds like you need to provide your own special member functions, no? E.g., for the copy constructor:
Foo(const Foo& other)
:lambda([this](){return this;})
{}
Whilst #lubgr answered the question for what I asked I think it is worth noting the other solution I have for my exact problem. The question stemmed from building a class to encapsulate lazy initialisation of members. My original attempt was
template <typename T>
class Lazy {
mutable boost::once_flag _once;
mutable boost::optional<T> _data;
std::function<T()> _factory;
void Init() const { boost::call_once([&] { _data = _factory(); }, _once); }
public:
explicit Lazy(std::function<T()> factory):_once(BOOST_ONCE_INIT),_factory(factory){}
T& Value() {
Init();
return *_data;
}
};
which can be used like
class Foo {
int _a;
Lazy<int> _val;
Foo(a):_a(a):_val([this](){return this->_a+1;}){}
}
Foo f(10);
int val = f._val.Value();
but has the same problem that I asked in my question in that this is a circular reference that doesn't get preserved for copy construction. The solution is not to create a custom copy constructor and possibly move constructor but to fix the Lazy implementation class so that we can pass in an arg to the factory.
The new implementation of Lazy for members is
template <typename T, typename TThis>
class LazyMember {
mutable boost::once_flag _once;
mutable boost::optional<T> _data;
typedef std::function<T(TThis const*)> FactoryFn;
FactoryFn _factory;
void Init(TThis const * arg0) const { boost::call_once([&] { _data = _factory(arg0); }, _once); }
public:
explicit LazyMember(FactoryFn factory):_once(BOOST_ONCE_INIT),_factory(factory){}
T& Value(TThis const * arg0) { Init(arg0); return *_data; }
T const & Value(TThis const * arg0) const { Init(arg0); return *_data; }
};
which is used as
class Foo {
int _a;
Lazy<int> _val;
Foo(a):_a(a):_val([](Foo const * _this){return _this->_a+1;}){}
}
Foo f(10);
int val = f._val.Value(&f);
and this doesn't have the circular reference problems and thus doesn't require a custom copy/move constructor.

Uninitialized value when dealing with shared_ptr

I'm sure this is very simple, but I'm rather new to smart pointers, and I couldn't find an answer to this.
Scenario is very simple:
I have a class A, that holds a shared_ptr to some object X:
class A{
shared_ptr<const X> _asX;
}
now after a series of function calls, I'm creating a new object of type B, that also holds this X. something like:
class B {
private:
shared_ptr<const X> _bsX;
public:
B(): _bsX(nullptr) // - maybe this is problematic {}
foo(shared_ptr<const X>& x)
{
_bsX = x;
// The line above gives me undefined behavior,
// and when I run valgrind I get "Conditional jump or move
// depends on uninitialized value(s)",
// telling me this is not the correct way to do things.
}
Note that it is deliberate the foo really sets the value of _bsX and not the constructor.
So as stated above - depending on the compiler, I something get segmentation faults - which usually means some value was not initialized, and later confirmed by valgrind.
So what should I do - I've tried using 'reset' etc. but I got so confused I'm asking for your help.
Could it be the const ? or the pass by reference ? or the '=' operator.
And while we're at it - should I be passing X with its wrapper (the shared_ptr) to foo, or should I pass the raw pointer, and then make it shared ? if so - could you please give an example. I tried that as well, and got errors.
Ok, I found the problem, and it's no related to smart pointers at all, but since I'm new to this - I thought it might be.
I'll leave this answer for future references. This is what I did (simplified):
class A{
private:
shared_ptr<const int> _num;
public:
A()
{
_num = make_shared<const int>(5);
}
const shared_ptr<const int>& getNum() const {return _num; }
void printNum()
{
cout << *_num.get() << endl;
}
};
class B
{
public:
struct C{
C() : _num(nullptr){}
void boo(shared_ptr<const int> & num) { _num = num;}
shared_ptr<const int> _num;
};
B() {}
void foo(shared_ptr<const int>& num)
{
cs.reserve(2);
for (uint32_t i = 0; i < 2 ; ++i) {
cs.push_back(C()); // This was missing.
cs[i].boo(num);
}
}
void printCNum()
{
for (C c : cs) {
cout << *c._num.get() << endl;
}
}
private:
vector<C> cs;
};
int main()
{
A a{};
shared_ptr<const int> xx = a.getNum();
B b{};
b.foo(xx);
a.printNum();
b.printCNum();
}
Silly me, I thought that when you reserve a vector of Objects (not pointers/references) it also calls their constructor. It turn out it's not. Specifically, I increased the capacity of the vector, but not its size.

How do i output properties of a pointer object in c++ (with 2 or more properties)

Class A
{
public:
A();
A(int x , int y);
Private:
int x;
int y;
}
Class B
{
public:
B();
A getApointerobject() const;
Private:
A *APointerObject;
int main()
{
B bObj;
cout << bObj.getApointerobject(); //i overloaded the << so that i can //output B objects but it crushes
}
//Class B implementation (This is where i struggle)
A getApointerobject() const {
return *getApointerobject;
}
In B::getApointerobject() you call it recursively. You should change to
A getApointerobject() const {
return *APointerObject;
}
Is B::APointerObject initialized before you call getApointerobject() method?
In getApointerobject you are trying to return the address of the method getApointerobject itself. I guess you code is not even compiling right now?
I guess you want to return your APointerObject
A B::getApointerobject() const {
return *this->APointerObject;
}
But be advised: Built in types, including simple pointers don't have a default constructor. So, since you don't initialise APointerObject in class Bs constructor, you would use a wild pointer. Which means you program would crash at runtime or worse (undefined behavior)

making public member read only

class A{
private:
int a;
public:
const int &ref = a;
};
int main() {
A obj;
obj.a = 20; // error cause private
obj.ref = 30; // not private but const so ERROR
return 0;
}
I'm trying to make a member variable accessible but read only through the interface. Currently I've tried this approach and it seems to compile fine. I made a const reference to my original variable int a and made it public. Is there anything that's wrong with this practice that I might be missing out? Or is this example safe and sound to use for practical purposes?
Nothing wrong with providing a member function with const correctness applied (and I've used that too and intend to do so always), but I'm asking is there any thing wrong with this way if I have to provide a variable that is only read-only.
Thankyou :)
class A{
private:
int a;
public:
const int &ref = a;
};
is there any thing wrong with this way if I have to provide a variable that is only read-only
There are at least a couple drawbacks with this design decision for class A.
1: Class Size
Also as Dieter Lücking mentions in a
comment:
increasing the size of the class, needlessly
2: Copy Semantics
It breaks the compiler generated copy assignment operator. For example, the following code behavior is generally desirable but doesn't work.
A obj1;
// ...
A obj2;
// make changes to 'obj2'
// Update 'obj1' with the changes from 'obj2'
obj1 = obj2; // This copy doesn't work!
More information:
Should I prefer pointers or references in member data?
Assignment operator with reference class member
Thinking in C++, 2nd ed. Volume 1 ©2000 by Bruce Eckel, 11: References & the Copy-Constructor
There are certain rules when using references:
A reference must be initialized when it is created. (Pointers can be initialized at any time.)
Once a reference is initialized to an object, it cannot be changed to refer to another object. (Pointers can be pointed to another object at any time.)
You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
It may be possible to implement a custom assignment operator but that's more code to maintain (i.e., another drawback in my opinion).
#include <iostream>
class A
{
private:
int a;
public:
explicit A(int value) : a(value) {}
A& operator=(const A& other)
{
a = other.a;
return *this;
}
const int& ref = a;
};
int main()
{
A obj1(10);
std::cout << "1: " << obj1.ref << "\n";
A obj2(20);
std::cout << "2: " << obj2.ref << "\n";
obj1 = obj2;
std::cout << "1: " << obj1.ref << "\n";
return 0;
}
The idiomatic way to address this issue is to use a proper accessor function.
class A {
private:
int a;
public:
int getA() const { return a; }
};
The standard way to do this in C++ is by making the actual member private but including a public 'getter' method for the interface, as below:
class A{
private:
int a;
public:
int get_a() const { return a; }
A() : a(20) {}
};
int main() {
A obj;
int n = obj.get_a(); // n = 20
return 0;
}
The user cannot set the value of A::a but can use A::get_a to retrieve its value.