Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional reference implementation

Tags:

c++

c++11

I have a problem here where I am not sure how to handle it. Firstly I am beginner. I have two constructors for a class and two reference variables declared but I can not use both references in one constructor. If cons1() is called I need ref1 to be used and if cons2 is called I need ref2 to be used. The problem is in what should I reference ref1 to, when cons2 is called and similarly what ref2 should reference when cons1 is called. I am not sure how to initialize these references. It can't be NULL. I am not sure if its a good idea to point to some invalid implementation. Should it? Is that even an option? How is such a problem handled in c++?

// A.cpp
Class A
A(Object1& a) : ref1(a) {}   - here how should ref2 be handled?
A(Object2& b) : ref2(b) {}- here what should ref1 reference?

// A.h
Object1& ref1
Object2& ref2

I need to use references here. I understand we can use pointers instead of references but the question is specific to using references.

like image 478
leonidus Avatar asked Feb 26 '26 05:02

leonidus


2 Answers

Since ref1 and ref2 are optional (not required), then it is better to use pointers, instead of references :

class A
{
  public:
    A(Object1& a) : ref1(&a), ref2(NULL) {}
    A(Object2& b) : ref1(NULL),ref2(&b) {}

 Object1 *ref1;
 Object2 *ref2;
};

but later you must check if the ref1 and ref2 are NULL.

like image 99
BЈовић Avatar answered Feb 27 '26 19:02

BЈовић


WARNING: the following is stupid and contrived. Why? Because so is the requirement to use references.

class base {
    virtual
    ~base();

    virtual
    void
    stuff_happens() = 0;
};
base::~base() = default;

class case1: public base {
public:
    explicit
    case1(Object1& o)
        : ref(o)
    {}

    void
    stuff_happens()
    {
        // we use ref here
    }

private:
    Object1& ref;
};

class case2: public base {
public:
    explicit
    case2(Object2& o)
        : ref(o)
    {}

    void
    stuff_happens()
    {
        // we use ref here
    }

private:
    Object2& ref;
};

std::unique_ptr<base>
make_base(Object1& o)
{ return std::unique_ptr<base>(new case1(o)); }

std::unique_ptr<base>
make_base(Object2& o)
{ return std::unique_ptr<base>(new case2(o)); }

// ...
{
    auto p = condition ? make_base(ref1) : make_base(ref2);
    p->stuff_happens();
}
like image 40
Luc Danton Avatar answered Feb 27 '26 19:02

Luc Danton