Gode that covers basics

Hi just getting into coding, can someone create or show me a code that covers basics so i can have reference to look back on. I would much appreciate the help.
Thank you.
Looking for something that includes stuff like:

constructors - default and/or parameterized, copy
reading from a file
destructor
accessors and/or mutators functions
Inherited class
etc
Thanks
The best on-line learning resource is learncpp.com
Hello. Try out this 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
// Default Constructor and Custom Constructor
// Default constructor is any constructor that takes
// no parameters. (It is created by default unless another is defined.
// in which case you would have to define a default constructor yourself.)

#include <iostream>
#include <string>

class MyClass
{
public:
    MyClass() // Default constructor
    {
        std::cout << "Default constructor called!\n";
        Text = "Hello, world!\n"; // Default string
        std::cout << Text << '\n';
    }
    MyClass(std::string text) // Custom constructor
    {
        std::cout << "Custom constructor called!\n";
        Text = text; // Custom string! :)
        std::cout << Text << '\n';
    }
private:
    std::string Text;
}; // <--- semi-colon is needed at end of class!

int main()
{
    MyClass obj; // Calls MyClass().
    MyClass obj2("Hello!!"); // Calls MyClass(std::string) (Custom constructor)
}


Output:

Default constructor called!
Hello, world!

Custom constructor called!
Hello!!


I hope this helps you. :)
Last edited on
For reading from file, try this:

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
#include <iostream>
#include <string>
#include <fstream>

bool isPrefix(std::string str, std::string prefix) // Test if one string is the first part of another
{
    return (str.compare(0, prefix.size(), prefix) == 0);
}

// Reads each line from a file, if a line starts with
// the parameter passed in (prefix) it returns that line!
std::string SearchForInFile(std::ifstream& stream, std::string prefix) 
{
   std::string data;
		
     while(std::getline(stream, data))
    {
        if(isPrefix(data, prefix))
       {
           return data.substr(prefix.size()); // substr(): removes a certain number of
                                           // characters from the beggining of a string.
       }
   }
   return "\0";
}

int main()
{
    std::ifstream stream("file.txt"); // File to read from (input file stream)
    std::cout << SearchForInFile(stream, "Text::");
}


Now, that code reads this file:
# file.txt
IgnoreThisLine::Hello, world!
Text::This will be printed to console!
AnotherIgnoredLine::Test!
Random Giberish

Output:
This will be printed to console!


Try it out! :)
Last edited on
Topic archived. No new replies allowed.