C++ Anatomy of a Class

class MyClass{
  //Access specifier: can be private, public, or protected
  public:
  //Data members: variables to be used
  float a;
  float b;
  
  MyClass(){} //Constructor - automatically called when new object created
  
  //Member functions: Methods to access data members
  float my_add(){
    return a + b;
  }
  
}; //class ends with semicolon
  • Memory is not allocated when a class is defined
  • An instance of the class needs to be created for memory allocation (new object created)
  • new is the C++ initialize function that allocates memory (creates pointer)
  • Classes can also be initialized as a declaration, i.e. MyClass m()
  • FIMS uses shared pointers to initialize classes
  • Once the class is instantiated, members can be accessed using
    • the dot(.) when class is declared
    • the pointer(->) when an instance of the class is created using new or is a shared pointer

Initialize and run a class

// [[Rcpp::export]]
void my_class_add(){ // use void since the main function has no return

  //create instance of class using a declaration
  MyClass m1;
  
  //members can be accessed using the . command
  m1.a = 1.2;
  m1.b = 2.4;
  
  Rcpp::Rcout << "m1.my_add() = " << m1.my_add() << std::endl;
  
  //create instance of class using a pointer
  MyClass *m2 = new MyClass();
  
  //members can be access using the -> command
  m2->a = 3.3;
  m2->b = 4.4;
  
  Rcpp::Rcout << "m2->my_add() = " << m2->my_add() << std::endl;
  
  //need to delete memory after use when initializing with new
  delete m2;
  
  // create instance of class with shared pointer
  // Note the type of the shared pointer is MyClass
  std::shared_ptr<MyClass> m3 = std::make_shared<MyClass>();
  
  //members can be access using the -> command
  m3->a = 4.2;
  m3->b = 1.7;
  
  Rcpp::Rcout << "m3->my_add() = " << m3->my_add() << std::endl;
}

The above two code chunks are saved in src/myclass.cpp. Note the following headers are added to the top of the file:

#include <Rcpp.h> // provides access to Rcpp library
#include <iostream> // provides access to std library
#include <memory> // provides access to shared pointers

The following runs the file using Rcpp:

Rcpp::sourceCpp("../src/my_class.cpp")
my_class_add()
## m1.my_add() = 3.6
## m2->my_add() = 7.7
## m3->my_add() = 5.9

resources:
geeksforgeeks
cplusplus