How to initialize an object with another object of different class?

How to initialize an object of class say "A", with an object of type say "B".
The following code give the error message "error: conversion from �A� to non-scalar type �B� requested"

#include <iostream>
using namespace std;

class B;
class A{
 public:
  A() { cout <<"\nA()" << endl; }

  A(A& rhs) { cout <<"\nCopyCtr:A&" << endl; }

  A& operator=(A& rhs){ cout <<"\nAssignment: A&" << endl; }

  operator B(A &rhs){
    B smplb;
    return smplb;
  }

};

class B{
 public:
  B() { cout <<"\nB()" << endl; }

  B(B& rhs) { cout <<"\nCopyCtrB&" << endl; }

  B& operator=(B& rhs) { cout <<"\nAssignment: B&" << endl; }
};

int main(){
  A a;
  B b = a;
  return 0;
}

Your 'operator B' doesn't quite work, so it can't convert.

Making an operator there is tricky, because A doesn't know what the contents of B are yet... So you just have to say that the function exists inside the class, then put the function definition after B is defined.

#include <iostream>
using namespace std;

class B;
class A{
 public:
  A() { cout <<"\nA()" << endl; }

  A(A& rhs) { cout <<"\nCopyCtr:A&" << endl; }

  A& operator=(A& rhs){ cout <<"\nAssignment: A&" << endl; }

  operator B();
};

class B{
 public:
  B() { cout <<"\nB()" << endl; }

  B(const B& rhs) { cout <<"\nCopyCtrB&" << endl; }

  B& operator=(B& rhs) { cout <<"\nAssignment: B&" << endl; }
};

A::operator B() {
        B smplb;
        return(smplb);
}

int main(){
  A a;
  B b = a;
  return 0;
}
1 Like