devfix
devfix

Reputation: 134

Constructor taking Base& is not called

I'm working on a simple program for Boolean algebra, but the double negation does not work as expected.

I have the following classes:

Operator:

#ifndef OPERATOR_H
#define OPERATOR_H

class Operator {
public:
    virtual int getArity(void) const = 0;
    virtual bool calc(void) const = 0;
};

#endif // OPERATOR_H

False:

#ifndef FALSE_H
#define FALSE_H

#include "operator.h"

class False : public Operator {
public:
    int getArity() const {
        return 0;
    }

    bool calc(void) const {
        return false;
    }
};

#endif // FALSE_H

Not:

#ifndef NOT_H
#define NOT_H

#include "operator.h"

class Not : public Operator {
public:
    Not(Operator& child) : m_child(child) {
        std::cout << "not constructor called" << std::endl;
    }

    int getArity(void) const {
        return 1;
    }

    bool calc(void) const {
        return !m_child.calc();
    }

private:
    Operator& m_child;
};

#endif // NOT_H

My main.cpp:

#include <iostream>
#include "operator.h"
#include "not.h"
#include "false.h"

using namespace std;

int main(int argc, char *argv[]) {

    False f;
    Not n = Not(f);
    Not d = Not(n);

    cout << "n.calc(): " << n.calc() <<endl;
    cout << "d.calc(): " << d.calc() <<endl;
    return 0;
}

Since d = Not(Not(False())) I expect it to be false.

The output is:

not constructor called
n.calc(): 1
d.calc(): 1 <== should be 0

Why is the constructor of the class Not not called with an object of type Not as child?

Upvotes: 11

Views: 657

Answers (1)

Not d = Not(n); invokes the copy constructor of Not, because the argument is also of type Not. The copy constructor's signature matches better and it's therefore selected.

Upvotes: 19

Related Questions