user2877289
user2877289

Reputation: 63

Passing objects by reference in C++

I am trying to pass an object (of class Stock) by const reference to a function of another class (called Algorithms).

//Algorithms.h
#pragma once

class Algorithms
{
public:
    Algorithms(void);
    ~Algorithms(void);
    int Algorithms::doAnalysis(const Stock&);
};

The implementation of doAnalysis is

#include "StdAfx.h"
#include "Algorithms.h"
#include "Stock.h"
#include <vector>

using namespace std;

Algorithms::Algorithms(void)
{
}

Algorithms::~Algorithms(void)
{
}

int Algorithms::doAnalysis(const Stock &S)
{
    //Do Something
    return 0;
}

The class Stock has the following constructors

public:
    Stock(std::string market, std::string symbol);
    Stock(std::string market, std::string symbol, std::string start_date, std::string  end_date);

I am getting the following error:

Error: declaration is imcompatible with "int Algorithms::doAnalysis(const<error-type> &)" declared at line 8 of  Algorithms.h

I understand that the class Stock is not being found. How should I declare the doAnalysis method in Algorithms.h so that it is found? Stock is not a derived class.

Thanks for your help. I am new to C++.

Upvotes: 0

Views: 179

Answers (3)

theAlias
theAlias

Reputation: 396

You could also just add #include "Stock.h" in Algorithms.h file and remove the include from the cpp file. Also you don't need Algorithms:: in the declaration of doAnalysis in Algorithms.h

Upvotes: 0

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14530

You have to add a forward declaration of the class Stock:

// Forward declaration
class Stock;

class Algorithms
{
public:
    Algorithms(void);
    ~Algorithms(void);
    int doAnalysis(const Stock&);
  //    ^^ <- Remove the Algorithms::
};

You can see here why a forward declaration is necessary in C++.

Upvotes: 7

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Put a forward declaration outside your class declaration:

class Stock;

class Algorithms
{
   // ...

Upvotes: 1

Related Questions