Calling function outside class from constructor

I have the following class, I understand I can declare the constructor in the class and define it outside as a solution however I want to put it in the class and keep the class in my header. If I create the class object like:

Sales_data readtest(cin)

I want it to call my read function, however my read function isnt yet defined, if I define/declare it before my class, my read function takes a class member that is not yet defined creating a paradox (think im using the word corrctly lol)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#ifndef MY_SALES_DATA_H
#define MY_SALES_DATA_H
#include <iostream>
#include <string>

using namespace std;




struct Sales_data{
    //constructors
    Sales_data() = default;
    Sales_data(const string& s, unsigned n, double d): bookNo(s), copiesSold(n), revenue(d*n){}
    Sales_data(istream& in){read(in,*this);} //<--PROBLEM HERE
    //members
       string bookNo = "";
       unsigned copiesSold = 0;
       double revenue = 0.0;
    //member default inline functions
Sales_data combine(const Sales_data &objectCombine);
string ISBN(){return bookNo;}
};

void read(istream& in, Sales_data &sdObject){
          in >> sdObject.bookNo >> sdObject.copiesSold >> sdObject.revenue;
          sdObject.revenue *= sdObject.copiesSold;
}



void add(Sales_data &objectAddTo, const Sales_data objectAddFrom){
        objectAddTo.revenue += objectAddFrom.revenue;
}

void print(const Sales_data objectToDisplay){
            cout << "Book Number: " << objectToDisplay.bookNo << endl
             << "Number Sold: " << objectToDisplay.copiesSold << endl
             << "Total Renvenue: " << objectToDisplay.revenue << endl;
}

//member function declared outside class.
Sales_data Sales_data::combine(const Sales_data &objectCombine){
        revenue += objectCombine.revenue;
        copiesSold += objectCombine.copiesSold;
        return *this;
}

#endif
Last edited on
It is enought that you forward-declare the class before you declare the function.
1
2
3
class Sales_data;

void read(istream& in, Sales_data &sdObject);
You rock dude, I didnt know but should have known by common syntax that I could forward declare a class as well as a function.
Topic archived. No new replies allowed.