Alex Brooks
Alex Brooks

Reputation: 1151

No known conversion from std::ostream* to std::ostream&

I have the following code:

class A {
public:
    ...
    C *func() { ... }
    void func2() { ... }
    ...
};

class B {
public:
    ...
    B(std::ostream &s, A *curr);
    ...
};

class C {
public:
    ...
    ostream *stream;
    ...
}

void A::func2() {
    ...
    std::ostream *astream = func()->stream;
    B *env = new B(astream, this);
    ...
}

However I am getting the following error on the B *env = new B(astream, this); line:

myfile.cc:680:86: error: no matching function for call to ‘B::B(std::ostream*&, A* const)’
myfile.cc:680:86: note: candidates are:
myfile.h:194:2: note: B::B(std::ostream&, A*)
myfile.h:194:2: note:   no known conversion for argument 1 from ‘std::ostream* {aka std::basic_ostream<char>*}’ to ‘std::ostream& {aka std::basic_ostream<char>&}’

I'm not sure how to solve this issue and would appreciate any input.

Upvotes: 0

Views: 2072

Answers (2)

Yury Schkatula
Yury Schkatula

Reputation: 5369

"astream" is a pointer. B() constructor expects a reference. So, the choice is:

  • Convert everything to pointers or references
  • Apply dereferenced pointer whenever you need a reference: *astream

Upvotes: 0

paddy
paddy

Reputation: 63481

Pointers and references are not the same thing. I might question exactly what you're doing here, but to solve your problem as it stands, do this:

B *env = new B(*astream, this);

When using a reference (eg std::ostream &), the syntax of normal variables applies.

In future, you can work out your mistake by reading the error message. The error "no known conversion" means you are trying to assign one type to another type that is incompatible. It tells you the two types (one is a pointer and the other is a reference). Now you know a little more about pointers and references, you will hopefully pick these errors up yourself in future. =)

Upvotes: 2

Related Questions