C++ Class Examples

Spread the love

C++ class constructor

class Entity{

public:

private:

Entity();

}


/*
	Lesson Setting up a Class. 
	Several ways to do so. Constructor parameters or
	initial vars in the public class

	Author	: Trevor Weir
	Date	: Mar 19, 2019 ( 1st day of spring )

*/


#include <string>
#include <iostream>

class Entity{

private:
	int m_score;
	std::string m_name;


public:
	Entity()
	:m_score(0), m_name("unknown"){};

	Entity(const std::string&amp; name)
		:m_score(0),m_name(name){};

	void Print(){
		std::cout << "Score = " << m_score 
				  << " Name: " << m_name 
				  << std::endl;
	}
};


int main(){
	std::string m_name;
	Entity e0;
	e0.Print();
	std::cout << "Give us a name, please : ";
	std::cin >> m_name ;
	Entity e1(m_name);
	e1.Print();
}


C++ Class Examples – What did that code mean?

Line 15, in the above c++ class code includes our first class structure Entity. Entity contains two private variable members m_score and m_name.

Private means that outside of the class, these two variables can’t be changed or even accessed. In order to access them from outside the class, an object needs to call a method inside the class in order to Print or display them.

The other new looking feature occurs on line 24 above or line 3 below where we have this utterly strange looking concept.


public:
    Entity()
    :m_score(0),m_name("Unknown"){};
    // What's this above?


:m_score(0), m_name(“Unknown”) are setting up the values of zero and Unknown to be associated with the variables m_score and m_name.

The above code is equivalent to the old way of doing it ( which still works, but get use to the new way please.

public:
    Entity(){
      m_score = 0;
      m_name = "Unknown";  // Old Way
    }
    // Entity()
    //     :m_score(0),m_name("Unknown"){}; New Way


Old way, New way comparison. Same result but just try to get used to the new way.


Line 29, void Print() is used to access the private variables that can’t be directly called or seen otherwise.

Line 30, a version of the object is called without any parameters.

Line 31, that same version e0 is asked to print its private members. Which it does and we get defaults of 0 and “Unknown” being printed.

Line 41, the program asks the user for a name. This name will be used to start another instance of the Entity object ( e1 ) and this time a different internal constructor will be called ( unbeknownst to the user ).

Line 44, the Entity e1 is asked to print itself – which it does happily and to no one’s surprise its name is the same one that the user just typed in a few seconds earlier.

Note: If the user types in a long first and last name combination, only the first name will be placed in the m_name variable because cin >> will only put the first word up until the space into the variable m_name. There is a fix for this, but we will get to that in another tutorial.


Class vs Structure – What’s the difference?

The primary difference between a c++ class and struct is the visibility of the internal elements. In a class, everything is private by default. Yes, that means we didn’t really have to use the private: structure above because those two variables m_score and m_name would have been private unless we put them in the public area.

In a struct everything is public by default.


Best way to learn this class structure thingy?

The best way to learn is is to do it first as pseudo code like this

// Comments. Let's just create the empty structure first

class Sample{
public:
private:
}; // don't forget the semi-colon

int main(){
    // instantiate the object here
    Sample doTheStuff;
}


Don’t be afraid to write the sets of lines above a few times, just to get the feel for it.

Then, start filling it in a bit but leave the variables for the next iteration

// Comments. Let's just fill in a little bit 
// of the code structure

class Sample{
private:
public:
    void Print(){};  // Add a function
}; 

int main(){
    // do work in here
    Sample doTheStuff;
    doTheStuff.Print();  // Call the object's function
}
// Test to see if it compiles


In this iteration, fill it in as much as you can remember

// Comments. Let's just create the empty structure first
#include <iostream>

class Sample{
private:
   int m_score;
   std::string m_name;
public:
   Sample() :m_score(0), m_name("Unknown"){};

   Sample(const std::string&amp; name)
      : m_score(0), m_name(name){};

   void Print(){
      std::cout << "Score = " << m_score 
                << " Name = " << m_name << "\n";
   };
}; // don't forget the semi-colon

int main(){
    // do work in here
    Sample doTheStuff; // has no parameters
    doTheStuff.Print();
    Sample doIt("Joanne Smithering"); // has a parameter
    doIt.Print();
}

Ready for a short c++ class Quiz ?


Welcome to your c++ Class & Structure

The difference between a c++ class and a struct?
Is this valid constructor code inside a class called Entity?
Entity()
   :m_age(23),m_height(176),m_name("Unknown"){}
Is this valid constructor code
inside a class called Entity?
Entity(){
   :m_age=23,m_height=176;
}
Structs are public by default, right?
Can a its private member be
changed by an assignment in main()?


Homework — C++ Classes. So How Was the Quiz

  • 1) We know you didn’t all do the quiz. Pls go back and do it.
  • 2) From memory, whats the difference between a class and a struct
  • 3) Try to creatively write a very small public class
  • 4) and instantiate that new class as an object from main()

Next Lesson ,

Top