is there a way to combine header file (made for a created class), actual class and the main function on the same page?
I'm trying to learn c++ code using my phone and I would really like to know this because it would help me, as I am mostly on my mobile and I would like to learn c++ where ever I travel. It would allow me to learn c++ quicker (hopefully), so please help.
For small programs, like learning exercises, it is permissible to include header info and class implementation in the main source file. Obviously, this is not the optimal way to do it, and you will run into problems when you try to scale things up. As long as you understand why you are doing what you are doing and the constraints you are under, I say go ahead. You can do something like this:
#include <string>
#include <iostream>
class MyClass
{
public:
MyClass(const std::string& n);
const std::string& getName() const;
private:
std::string name;
};
MyClass::MyClass(std::string) : name(n)
{}
const std::string& MyClass::getName() const
{
return name;
}
int main()
{
MyClass object("The Name");
std::cout << "My object has the name " << object.getName() << std::endl;
}
Note: not compiled or tested.
Pretending for the moment that the member functions are significant enough to warrant not being inlined, this code would normally be broken up into 3 files. but you can cram it all into 1 as shown here.