About "error: assignment of data-member ‘A::pCost’ in read-only structure".

Hi there,

I got an error as above.

My requirements are: I need a derived class A from class B. In A, there are two member functions, i.e., Initialise() and GetCost(). The Initialise() initialises pointer pCost pointing to an array, and every invocation of GetCost() change the array pCost pointing to.

1. I know that a const function GetCost() can not change the value of the member variable, e.g., pCost. However, I think there is a way to use pointer to solve the problem but I don't know how to do it.

2. The GetCost() in class A is overriden from a virtual function in class B. Can I remove the 'const' after the function?

The codes are shown below, and any suggestions would be appreciated.

Class A : public B
  void Initialise(void);
  void GetCost( const CostType & cost ) const;
  double* pCost;

void A::Initialise(void)
  double iniCost[12] = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0 };
  pCost = iniCost;

void GetCost( const CostType & cost ) const

  double updatedCost[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  updatedCost = cost; // error as well
  pCost = updatedCost; // error: assignment of data-member ‘A::pCost’

Line 24 "updatedCost = cost" is an error because you are trying to store a "CostType" to a double pointer. How is "CostType" defined? This looks like an attempt at a template, but it's not implemented correctly.

The error on Line 26 is the result of attempting to modify an object's data member inside a const function. That's not legal. A "get" type function shouldn't modify a value unless you have an extremely good reason to. You should take this action and put it in an "UpdateCost" function instead.

Also, pCost is a dangling pointer. In both A::Initialise() and GetCost() you have tried to store locally-scoped pointers to member pointers. When the function ends, the values those pointers point to are destroyed. If you try to access, for example, pCost[2] at a later time, you will get a seg fault.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.