How would i extend the FILE class to use its methods? In other words, how can i use all of the functions that are provided with the default FILE object and still have the same functionality that mimics the actual functions?
class myFile
{
File *_f;
public:
myFile(File *f){ /*open the file here, then make _f=f;*/ };
virtual ~myFile(){ /*close the file here*/ };
// and can add more methods here
}
Related
As an example lets say I have a class called File. Now file can be opened as binary or text. My constructor is currently File(const char*filename). Let's suppose the implementation of open is completely different binary and text. How the heck do I construct this?
I thought about using a static function but I don't want to return a pointer. I could pass in a pointer but I rather not allow a class be constructed without actually initializing it.
I was thinking about having an enum or bool in the constructor but it feels 'wrong' to me (and the way I may do this). I could have a different class name for binary and text and have both inherit a base implementation (or the other implementation) even though the only difference is the constuctor.
What's the most idiomatic way of doing this in C++?
Add a flag
enum class open_mode
{
binary,
text
};
File(const char* filename, open_mode mode);
or use a tag
struct binary_tag { };
struct text_tag { };
File(const char* filename, binary_tag);
File(const char* filename, text_tag);
Two idiomatic ways are a factory function (nothing forces you to return a pointer), or tag dispatching (which is used in the standard library, for example in std::variant).
// Factory functions
struct File {
static File openText(char const *filename);
static File openBinary(char const *filename);
};
// Tag dispatching
struct open_as_binary_t {} constexpr open_as_binary;
struct open_as_text_t {} constexpr open_as_text;
struct File {
File(char const *filename, open_as_binary_t);
File(char const *filename, open_as_text_t);
};
I could have a different class name for binary and text and have both
inherit a base implementation (or the other implementation) even
though the only difference is the constuctor.
Yes, in general, I can propose to use the polymorphism.
It is always clean, easy maintainable, extensible and understandable. Very flexible.
The best for creating something could be the factory design pattern.
Example:
class File{ protected: File(); ... }; // make constructor protected!
class BinFile : public File;
class TextFile : public File;
Then you could use it in the ordinary way:
File *f = new BinFile;
File *f = new TextFile;
Place all common stuff in class File
Implement any specific functionality per child class.
Then you could engage some factory method like:
File * OpenFile( String pathToFile, "TextFile" );
File * OpenFile( String pathToFile, "BinFile" );
In general, in this way, the code is very flexible.
Why not even simpler:
File(const char *filename,const char *mode)
{
fl=fopen(filename,mode);
//
}
And simply call with myFile = File("log.txt","rt");
I have a class A which handles file by opening, reading and closing. I also have another class B that use A to read file. B has instance of A as private member data. I want to reuse the a and use it to read multiple files using this instance. I also read some where that we cannot copy any of the stream. So my question is how can I handle class A to read multiple files in B?
class A{
A(std::string s){
f.open(s);
}
void read_file(){
/// read file
// close after reading
f.close();
}
private:
std::ifstream f;
};
class B{
B(std::string s_):a(s_){}
void read_multiple_files(){
a.read_file();
// now lets read another file
a = A("another_file_1.txt");
a.read_file();
////////////////////
// now lets read another file
a = A("another_file_2.txt");
a.read_file();
}
private:
A a
};
This is probably a design issue. There seems no reason for B to hold an instance of A unless it needs to keep a file handle across different method calls.
Instead, simply create an A to read each file:
class B {
void read_multiple_files() {
// read our files
auto result = A("another_file_1.txt").read_file();
auto result_2 = A("another_file_2.txt").read_file();
...
}
}
I have a class A which has a function called openFile(const char * name), which opens a file.
I have two child classes Reader and Writer
Reader opens the file in a reading mode.
Writer opens the file in a writing mode.
I'm using fopen to open the file.
I would like to open this file in either a reading mode or a writing mode, depending on which child class is calling this method.
Is it possible to do this without sending any extra parameters to the parent class?
Of course, something like this is exactly what inheritance is meant to do:
class A {
public:
virtual void openFile(const char* name) = 0;
// If A cannot open a file on its own, else implement it
// rest of implementation
};
class Reader : public A {
public:
virtual void openFile(const char* name) {//open file in read mode}
//rest of implemenation
};
and handle Write analog. Then, given a pointer or reference of type A* or A& pointing or referring to one of the children, the right function will be chosen:
A* a1 = new Reader{};
A* a2 = new Writer{};
a1->openFile("test.in"); // calls Reader.openFile()
a2->openFile("test.out"); // calls Writer.openFile()
I have a number of classes that use identical generic functions/methods. At present I have coded these methods for each class, but this involves unnecessary duplication. So I want to move these methods to a Utils class that can be accessed by all classes that need to make use of these methods. I think this can be done with Generic or with Template, but I don't have an example that I can understand.
This is what I do now (left out all non-essentials):
Genome.h:
ref class Genome
{
public:
List<wchar_t>^ stringToList(String^ inString); // convert string to List with chars
};
Genome.cpp:
List<wchar_t>^ Genome::stringToList (String^ inString)
{
List<wchar_t>^ tmpList = gcnew List<wchar_t>();
int i;
for (i = 0; i < inString->Length; i++)
tmpList->Add(inString[i]);
return tmpList;
}
and a typical method call would look like this:
cString->AddRange(stringToList(aLine)); // genome string is stored as one line
where cString is of type List<wchar_t>^
So if I were to move the stringToList method to a Utils.h and Utils.cpp class, what would the code look like, and how do I the call this and other Utils methods in classes Genome.cpp and others?
Thanks, Jan
I put my utility functions in a class that I mark as abstract sealed. Since the class is abstract sealed, you cannot create instances of it, therefore all members have to be declared as static. The result is equivalent of having free functions.
E.g. in the header you will have
public ref class MyUtils abstract sealed
{
// ........................................................................
private:
static MyUtils ();
public:
static System::Double CalculateAverage ( cli::array<System::Double>^ arrayIn );
};
and in the .cpp
MyUtils::MyUtils ()
{
}
System::Double MyUtils::CalculateAverage ( cli::array<System::Double>^ arrayIn )
{
// the code doing the calculation...
}
You call this method as you call any static method
e.g.
cli::array<System::Double>^ values = gcnew cli::array<System::Double>(5);
// ...
// put some data in the array
// ...
System::Double average = MyUtils::CalculateAverage ( values );
Of course you can have generic methods as member of this class too.
I have written a library (doesn't matter what it does), which obviously has its header file. Now, I want to hide private elements of that header file, so if I provide my library to somebody, he/she should only see public members (preferably no class definition, nothing other than function definitions). One way would be creating C-style header, which will contain some kind of "init" method which will be used to create an instance of the actual class of library and the user will have to pass a pointer of that object to every function to do the job.
Is it a good practice?
Are there any other publicly accepted ways of doing something like that?
Thanks in advance.
In addition to the Factory pattern (which, in my opinion, can become unwieldy), you can also hide your private members behind a PIMPL (Pointer to IMPLementation):
// Interface.hpp
class Implementation;
class Interface {
public:
Interface() : pimpl(new Implementation()) {}
void publicMethod();
private:
std::unique_ptr<Implementation> pimpl;
};
// Interface.cpp
class Implementation {
public:
void PrivateMember();
};
void Interface::publicMethod() { pimpl->PrivateMember(); }
This has the advantage of hiding implementation, at the cost of a single pointer indirection, not much different from the typical inheritance-based Factory pattern.
This can also be ABI stable. Changes to your implementation won't affect linkage, since no changes will ever be visible to the rest of the program. This is a good pattern to use when implementing shared objects, for example.
It's also a common C++ idiom, so other C++ programmers will recognize it without question.
In the case of a class which will follow the Singleton pattern, you can avoid exposing the PIMPL at all, and simply write the entire implementation in an anonymous namespace in your .cpp file, where you can put as much state and private functions as you wish, without even hinting at it in your interface.
You can create a publicly-visible interface. Create an abstract class with the functions you want to expose, then have your implementation extend it.
For example, an interface:
class Interface {
public:
virtual void publicMethod() = 0;
...
};
And the implementation:
class Implementation : Interface {
public:
virtual void publicMethod();
private:
int hiddenMethod();
};
Then you only export the symbols for Interface. Now, in order for the user of the library to get instances of Interface which are actually Implementations, you need to provide a factory:
class Factory {
public:
//can create and return an Implementation pointer, but caller will get an Interface pointer
std::shared_ptr<Interface> getImplementationInstance();
}
Base on Eric Finn's answer, you can just declare an interface class to hold all your public methods which considered to be your API, and hide all implementations and private members/methods in implementation class which inherits interface class, here's the example:
Your header file: my_api.h
// your API in header file
// my_api.h
class interface {
public:
static interface* CreateInstance();
virtual void draw() = 0;
virtual void set(int) = 0;
};
your implementation(shared library): my_api.cpp (users won't see this when you make it a shared library)
So you can hide all your implementation and private methods/members here
#include "my_api.h"
// implementation -> in .cc file
class implementation : public interface {
int private_int_;
void ReportValue_();
public:
implementation();
void draw();
void set(int new_int);
};
implementation::implementation() {
// your actual constructor goes here
}
void implementation::draw() {
cout << "Implementation class draws something" << endl;
ReportValue_();
}
void implementation::ReportValue_() {
cout << "Private value is: " << private_int_ << endl;
}
void implementation::set(int new_int) {
private_int_ = new_int;
}
interface* interface::CreateInstance() {
return new implementation;
}
How user uses your API:
#include <iostream>
#include "my_api.h"
int main(int argc, const char * argv[])
{
using namespace std;
interface* a; interface* b;
a = interface::CreateInstance();
a->set(1);
b = interface::CreateInstance();
b->set(2);
b->draw();
a->draw();
return 0;
}
Output:
Implementation class draws
Private int is: 2
Implementation class draws
Private int is: 1
In this pattern, your api is just an abstract class which works like a factory, you can also implement the virtual method in different classes and specify which instance you would like to call.
I think you need to create Dynamic Link Library (dll).
Please take a quick look at this link:
You might want to take a look at the envelope/letter idiom, bridge design pattern, or proxy pattern. Basically, you would create an outer (public) class that would just forward your public method calls to the inner (private) class. Your InnerClass.h header only needs to be visible/known to your OuterClass.cpp and InnerClass.cpp source files.
Each of these patterns provides a mechanism of separating the implementation from the interface so that the caller is not coupled to the implementation. Sometimes this is desired to reduce compiler dependencies on large C++ projects. Another common reason for wanting to do this is just when you want to hide the implementation details so that the caller only sees a single opaque pointer.
======= OuterClass.h =====
class InnerClass; // forward declaration is all that's needed
class OuterClass {
private:
InnerClass *pInner;
public:
InnerClass();
bool doSomething();
};
======= OuterClass.cpp ======
#include "OuterClass.h"
#include "InnerClass.h"
OuterClass::OuterClass() :
pInner(new InnerClass())
{
}
bool OuterClass::doSomething()
{
return pInner->doSomething();
}
There actually is a way to do this without having to use classes. I had the same issue and here is a very simple solution:
Just put your private things into the .cpp file. Your header file will look something like this:
// These will be visible to everyone using this library
void function();
int someNumber = 2;
and your .cpp file:
void function() {
// whatever this function does
}
// This will be only visible to the library itself
static void secretFunction() {
doSomeSecretStuff;
}
static int PIN = 1234;
// Okay, if you write this Number into your library and expect it to be safe,
// then screw you, but at least no one will be able to access it with code
When calling the "public" functions from outside you now don't need any instance of that class anymore: Just place the library in the correct directory and include it, but you probably have already taken care of that) and call the functions by their names in the Lib.h file. In the instance of this example it would look something like this:
#include "Lib.h"
int main(int argc, const char * argv[]) {
function();
return 0;
}
Thanks to Edgar Bonet for helping me find this solution on the Arduino Stackexchange!