Constuctor taking Base& is not called

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: