0

Hello I have made class gabka and a function f1 to which I would like to pass an array of pointers to fill this array with gabka objects but I get weird error. How to correct it?

error:

cannot convert from gabka to int

the code :

#include <iostream>
using namespace std;
const int n = 4;
class gabka {
public:
    float woda;

    gabka(){
        woda = 0;
    }

void f1(gabka t[n]){
        for(int i = 0; i < n; i++){
            t[i] = new gabka();
        }
    }
};

int main() {
    gabka** t = new gabka*[n];

    return 0;
};
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Yoda
  • 17,363
  • 67
  • 204
  • 344
  • 1
    I bet that you were also told what line of your code causes that error. ;) – Drew Dormann Apr 09 '13 at 14:21
  • 1
    Whatever C++ book you are learning with, throw it way, it’s complete and utter crap, and it’s teaching you horrible C++. [Get a proper C++ book.](http://stackoverflow.com/q/388242/1968) – Konrad Rudolph Apr 09 '13 at 14:24

2 Answers2

1

Your f1 function takes an array of gabka objects, and you are trying to assign a gabka* to each one of them. You need to decide what you want to pass to f1. For example,

void f1(gabka t[n]){
    for(int i = 0; i < n; i++){
        t[i] = gabka(); // assign default constructed gabkas
    }
}

or

void f1(gabka* t[n]){
    for(int i = 0; i < n; i++){
        t[i] = new gabka();
    }
}

In the latter case, bear in mind you have to call delete on all the elements of t.

It isn't clear what you are intending to do with your code, but, as a general rule, in C++ you should avoid raw pointers and manual dynamic allocation. Prefer standard library containers over dynamically allocates arrays or arrays of dynamically allocated objects.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1
t[i] = new gabka();

t is an array of gabka, not an array of gabka*.

Either change the declaration of t to be an array of gabka*, or fill it with gabka instances.

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40