Cannot call member function without object

Hi, I'm having problem calling a function from a class in the main.cpp. Could someone tell me how to fix this please?

1
2
3
4
5
6
7
8
9
10
11
12
//main.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "CD.h"

using namespace std;
class CD;

double mind, maxd;
CD dwindow = CD::setd(mind, maxd);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//CD.h

#ifndef CD_H_
#define CD_H_

#include <string>
#include <vector>

using namespace std;

class CD {
public:
	virtual ~CD();
	CD(Data, double, double);

	/// Virtual copy constructor.
	virtual CD* clone() const = 0;

	void setd(double mind, double maxd);
};
#endif 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
//CD.cpp

#include "iostream"
#include "CD.h"

using namespace std;

//method: set min and max d's
void CD::setd(double mind, double maxd) {
	_mind = mind;
	_maxd = maxd;
}
CD::~CD() {
}


If I set the method to be static, then I get the following error: "cannot declare member function 'static void CD::setd(double, double)' to have static linkage".
Thank you in advance for your help!
A class represents a "thing", but the class itself is not actually a thing. You need to create objects of that class. Each object is its own thing.

For example... string is a class. This means that you can have multiple "objects" of type string. Each has its own string data.

1
2
string foo = "hi";
string bar = "there";


Here, foo and bar are both strings. Now you can call member functions (such as the length function) by using the object name and the dot operator:

 
size_t len = foo.length();  // get the length of the foo string 


But without an object, a call to length makes no sense:

1
2
3
4
size_t len = string::length();  // ??  what string are we getting the length of?
  //  is it foo?  is it bar?  is it something else?
  // doesn't make any sense!
  //  so the compiler will give this line an error. 



This is basically what you're doing. You're trying to call setd, but you're not telling the compiler which CD object you want to set. So it spits that error at you.

You'll need to create an object:

1
2
3
CD myCD;

myCD.setd( ... );
Last edited on
where do I create that object?
Objects are just like normal variables (like ints, doubles, etc). Declare it wherever you need to use it.
Topic archived. No new replies allowed.