Objects and Classes

  1. Overview
    1. class - Data type that groups data and functions that operate on the data
    2. object - An instance of a class. Ex: MyClass someObject;
    3. Classes and object are fundamental OOP concepts
  2. Defining a class
    1. Use class keyword to define a class
    2. Use public keyword to define public member functions, which indicate the operations can be performed on an object
    3. Use private keyword to define private data members, variables that public member functions can access but are inaccessible outside the class
    4. Example Student class
      class Student
      {
      	// public member functions
      	public:
      		void SetName(string stuname)
      		{
      			name = stuname;
      		}
      
      		void SetGpa(double stugpa)
      		{
      			gpa = stugpa;
      		}
      
      		void Print()
      		{
      			cout << "Name: " << name << "\nGPA: " << gpa << endl;
      		}
      
      	// Private data members 
      	private:
      		string name;
      		double gpa;
      
      };  // Don't forget the semicolon!
      
    5. Declare a Student object
      // s1 is a new Student 
      Student stu;
      
    6. Use the data member access operator (.) to call member functions
      stu.SetName("Bob");
      stu.SetGpa(3.0);
      stu.Print();  
      
    7. Private data members are not accessible outside the class
      // WRONG - Syntax error!
      stu.name = "Bob";
      stu.gpa = 3.0;					
      
  3. Separation of definintion and declaration
    1. Most programmers prefer to separate the declaration of member functions from the definition to make the class definition more succinct
    2. Definitions require prefacing the member function name with the class name and scope resolution operator (::). Ex: ClassName::FuncName(...)
    3. Example that separates member function declarations and definitions
      class Student
      {
      	public:
      		// Declarations
      		void SetName(string stuname);
      		void SetGpa(double stugpa);
      		void Print();
      
      	private:
      		string name;
      		double gpa;
      };  
      
      // Definitions
      void Student::SetName(string stuname)
      {
      	name = stuname;
      }
      
      void Student::SetGpa(double stugpa)
      {
      	gpa = stugpa;
      }
      
      void Student::Print()
      {
      	cout << "Name: " << name << "\nGPA: " << gpa << endl;
      }
      
    4. Some programmers prefer to only separate function declarations and definitions for multi-line functions
    5. Inline member function - Function definition that appears in the class declaration
      class MyClass 
      {
      	public:
      	 	// inline member function
      		void MyClass::SomeFunc() 
      		{
      			somevar = 0;
      		}
      
      		void OtherFunc();
      	...
      };