Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
Core Avatar asked Oct 29 '18 13:10

Core


1 Answers

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.

like image 187
Angew is no longer proud of SO Avatar answered Nov 12 '22 01:11

Angew is no longer proud of SO