OOP

I am a new first semester student. I wanted to work with OOP. I have a question, how can I make one class function accessible by another ? Below is my code:

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
51
52
53
54
55
#include <iostream>
#include <fstream>
using namespace std;
#include <filesystem>
namespace fs = std::filesystem;

// Class to define the properties
class File {
public:

	// Function declaration of input() to input info
	void input();

	
	//Copy the file read by input()
	void output();
};

// Function definition of input() to input info
void File::input()
{
	
	const std::filesystem::path src = "Input.txt";
	cout<<"File copied";
	
}

// Function output() to save the file to destination
void File::output()
{
	const std::filesystem::path dst = "Hello.txt";
	//But here source wont be accessible
    	std::filesystem::copy_file(src, dst, std::filesystem::copy_options::overwrite_existing);
		

	// Output is the stored file
	cout << "\nFile stored"<<endl;
}

// Driver code
int main()
{
	// Creating object of the class
	File object;

	// Copying source file contents
	
	object.input();

	//Outputting data means saving it in a file. 
	object.output();

	return 0;
}


I want input() to be accessible by output(). How can we do that
Last edited on
You mean you want to call input() from output()? If that is what you want you just write the function name followed by parentheses without anything in front.

1
2
3
4
void File::output()
{
	input();
}
I get the error:
‘src’ was not declared in this scope
The issue is that src is defined locally in function input() - so can't be used in function output(). Perhaps make src a member variable? Perhaps:

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
#include <iostream>
#include <fstream>
using namespace std;
#include <filesystem>
namespace fs = std::filesystem;

// Class to define the properties
class File {
public:
	// Function declaration of input() to input info
	void input();

	//Copy the file read by input()
	void output();

private:
	std::filesystem::path src;
};

// Function definition of input() to input info
void File::input() {
	src = "Input.txt";
}

// Function output() to save the file to destination
void File::output() {
	const std::filesystem::path dst = "Hello.txt";

	std::filesystem::copy_file(src, dst, std::filesystem::copy_options::overwrite_existing);

	// Output is the stored file
	cout << "\nFile stored\n";
}

// Driver code
int main() {
	// Creating object of the class
	File object;

	object.input();

	//Outputting data means saving it in a file.
	object.output();
}

Topic archived. No new replies allowed.