jazzybazz
jazzybazz

Reputation: 1887

Returning the address of a vector element C++

I have 2 classes, one is called A, the other B.

In class B there is a vector of elements of type A. Let's call it vectorofAs.

I am writing a function in B that returns a pointer to A, and this A is an element of the vector.

Here is the function

A* B::function() const {
 *do something to find the needed element index i*
 return &vectorofAs[i];
}

Shouldn't this return the adress of the ith element of the vector? Intellisense says "Error: return value type does not match the function type"

Upvotes: 0

Views: 5613

Answers (2)

SoapBox
SoapBox

Reputation: 20609

You didn't specify, but I'm assuming: vectorOfAs is defined as a member of class B with the type std::vector<A> .

In that case, the issue is that your function is defined const, which means that all members of the instance of B are also const inside this function. That means that your vectorOfAs is a const std::vector<A>. That means that the type of &vectorOfAs[i] is A const * not A * as your function is returning.

You have two options:

  1. Change the function return type to A const *
  2. Make the function non-const.

Upvotes: 4

BeniBela
BeniBela

Reputation: 16917

You have marked the function as const.

So this is a const B*, vectorofAs becomes a const vector<A>, and vectorofAs[i] is const A& and &vectorofAs[i] is a const A* which is not the same as an A*

So either put a const in front or remove the one at the end

Upvotes: 0

Related Questions