user2252786
user2252786

Reputation: 1635

Mixing OOP with structural code

I have a couple of classes in different files. I want to use simple C read from a file mechanism in main() function - just read two integers from two files, that's all.

Now, should I create a separate File class and handle it from there?

Should I create standard function in separate "file.cpp" file?

Should I write these 3 - 5 lines of code in main() directly?

Upvotes: 0

Views: 217

Answers (3)

Joseph Mansfield
Joseph Mansfield

Reputation: 110668

I think you mean that you're mixing OOP with procedural programming. If so, good. C++ is designed to leverage both of these together.

If you want to write a function that does not have any state, don't make it a member of a class. Just write a free function called read_values_from_file or whatever you want. It's definitely a good practice to identify individual responsibilities in your code and factor them out into functions.

Which file you should put it in depends on whether you'll reuse it at all. If you're only ever going to use it at the beginning of main, just put it in main.cpp. Don't give it it's own file just for the sake of it. Otherwise, if you want to use the same function across multiple translation units, it might be useful to place its declaration in a header file and its definition in an implementation file.

Regardless of where you put it, do not make this function a member of a class. That's what Java programmers do because they have no choice. C++ trusts you to know when it is most appropriate to create a class: when you have state.

However, I don't imagine you have a very good reason for using any C library functions to read from the file. There's no reason you can't write procedural code that uses the C++ standard library. Just use the file streams, such as std::istream, to read the values.

Upvotes: 2

Alex
Alex

Reputation: 15333

This task is so small it's it's hard to say if 'best practices' apply.

Make it work for now, using scanf or std::cin or whatever is convenient and if you find yourself needing more functionality later then start designing something more robust.

Don't waste a bunch of time overengineering something simple until you know you're going to need those extra features.

Upvotes: 0

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

Since the question is tagged as c++, I suggest checking the topic of c++ streams. I don't see why would you have to write file reading related classes.

Upvotes: 1

Related Questions