Skip to the content.

Classes in C++ and C#

Back to Homepage
Back to Week 1


Review

Encapsulation

Class Designer vs. Client


SOLID

Computing Systems!


C++

Elements to C++:

#include <iostream>
// comments in code

int functionName(int variable){
  // stuff
}

class className {
  //stuff
}

struct Person {
  //stuff
}

Example struct

struct Point{
  int x;
  int y;
};

Point p;
Point p2;

p.x
p2.x

Example Class

class Point{
  private:
    int x;
    int y;
   
  public:
    int getX() const;
};

Point p;
Point p2;

p.x
p2.x

When function is a member of a class, methods (member function) get access to other private variables in the class

If you have a getter can replace the code later. Keep variables private. Getters public

.h files contains skeleton of the class

.cpp file shows implementation

Constructor and Destructors

class Point{
  Point(int, int); // Constructor
  ~Point(); // Destructor
  
  int x;
  int y;
  
  public:
    int getX() const;
};

Memory Allocation

Stack is efficent but infelxible


Heap much more flexible

Can use stack, but once you leave the function, the stack gets cleaned up When using heap have to manually delete or else you get memory leaks

Point p; // goes on stack
Point *p2 = new Point(3,4); // pointers go on heap, new says find memory on heap

C#

Value types

Reference types

Has a garbage collector

no equivalent to a destructor


private static void downloadGoogle()
{
  WebClient client = new();
  string webpage = client.DownloadString("https://www.google.com/")
  File.WriteAllText("google.html", webpage);
}

WIth C# all class related stuff goes into one file a .cs file

internal class Point
{
  private int x; // each individual thing needs to be tagged with public/private
  private int y;
  
  public int X { get; private set; } // Properties: things that look like fields but have built in getters and setters
  public int Y { get; private set; }
  
  public Point(int x, int y)
  {
    this.x = x;
    this.y = y;
  }
}

namespace helps organized code, if multiple classes with same name

static methods dont have to create an instance to used that method

cant have null variables without ?


internal calss PizzaOrder
{
  private string? cheeze;
  private string? sauce;
  private bool isGlutenFree;
  private int diameter = 14;
  private List<String> toppings;
  
}