fnc("something") = Obj

Started by
5 comments, last by rip-off 15 years, 5 months ago
My function fnc returns a X* Type object. So can I use fnc("something") = Obj if Obj is of type X* or XDerived* I've already tried and compiler fired error saying.
error: lvalue required as left operand of assignment
On the line where I do fnc("something") = Obj;
Advertisement
Quote:Original post by nlbs
My function fnc returns a X* Type object.
So can I use fnc("something") = Obj
No.

Unless your function returns a reference to a pointer, you can't assign to its return value like this. So, for example:

X* &get(){  static X* internal;  return internal;}get() = new X();

Thanks fro that Information.

Hmm In method signature I can use.

Js::JType* &operator()(const string& key);

But what would I put in cpp

Js::JType* &Js::Object::operator()(const string& key){

fires Compilation errors.
What compilation errors?
jobject.cpp:37: error: invalid initialization of reference of type 'Js::JType*&' from expression of type 'Js::JType* const'


for the following line

Js::JType* &Js::Object::operator()(const string& key){


EDIT

Sorry the error is for a different reason
As I've already posted I am not deleting it.

I think &Js::Object::operator()(const string& key) doesn't causes the problem
overlooked the error message
In that function I've return it->second.
it is of type Iterator (non-const Iterator) and on that line Its firing that above error.

jobject.cpp:37: error: invalid initialization of reference of type 'Js::JType*&' from expression of type 'Js::JType* const'


Now from where it getting the const I am not able to understand.

it is an iterator to a stl map.
std::map<std::string, Js::JType*>

EDIT

However Casting it directly works
return (Js::JType* &)(it->second)

[Edited by - nlbs on November 5, 2008 9:29:52 AM]
You need to be extremely careful when casting, especially a C-style cast.

This compiles:
#include <map>#include <string>#include <stdexcept>struct Type{};struct Example{	Type *& foo(const std::string &s)	{		std::map<std::string, Type *>::iterator it = map.find(s);		if(it != map.end())		{			return it->second;		}		else		{			throw std::runtime_error("blah");		}	}private:	std::map<std::string, Type *> map;};


Can you post a minimal* example that exhibits the behaviour you are seeing?

* This means I should be able to copy and paste the code into my IDE and build it. No external headers etc.

This topic is closed to new replies.

Advertisement