I left questions in the comments strategically, since I think it's easier to answer questions this way.
Basically what my small class does is abstracts away functionality that was originally in a function.
This class reads json form a file and creates an object which I can use to traverse the json. I understand that if something can be made into a function it shouldn't be made into a class, but I need to practice.
Below I outlined things I'm looking for. Choose one or choose all.
Looking for:
- Did I use references "&" correctly
#include
header files correctly- A way to initialize object like so:
Root rate("test.json", ["query"]["results"]["rate"])
(syntax can be different) - Best practice advice
Not looking for (at least not yet):
- Exceptions and Error handling
- Advice form C programmers
root.h
#ifndef ROOT_H #define ROOT_H // Should header files always be included in root.h as opposed to root.cpp? #include <fstream> #include <string> // Seems like I do not need to include this string container, why? //is it because json/json.h contains it? #include "json/json.h" // Would I ever create a class with a dependency like this one? // jsoncpp.sourceforge.net/annotated.html class Root { private: std::ifstream m_json; public: Json::Value m_root; Json::Value m_query; Root(const std::string&); ~Root(); }; #endif // ROOT_H
root.cpp
#include "root.h" Root::Root(const std::string & filename) : m_json(filename, std::ifstream::binary) // Is std::ifstream::binary ok to put it in here like this ^? // It's working, but would that be good practice? { m_json >> m_root; m_json.close(); // Do I need .close() here? } Root::~Root(){}
main.cpp
#include <iostream> #include "root.h" int main() { Root rate("test.json"); rate.m_query = rate.m_root["query"]["items"]; // Is it ok to assign member to a member like so, // as opposed to just a variable? // How can I instantiate my object like the line below? // Root rate("test.json", ["query"]["results"]["rate"]); // Syntax does not have to match precisely? for(const auto & it : rate.m_query) { std::cout << it << std::endl; } }
test.json
{ "query": { "count": 3, "items": [ {"item": "4"}, {"item": "3"}, {"item": "2"} ] }