Menu
CoddyTech

Classes and Instances

Lesson 32 of 48 in Coddy's C++ for Lua Developers course.

A Lua object is usually just a table: any field can be added at any time, a missing field reads as nil, and a class is a convention built from a metatable whose __index holds the shared methods. A C++ class or struct declares its data members and member functions up front, so the compiler fixes every object's layout and rejects a member name that does not exist. C++ objects can be stored directly as values. Member functions operate on their object; class and struct differ in default access.

Lua

local Parcel = {}
Parcel.__index = Parcel
function Parcel.new(label)
  return setmetatable({ label = label }, Parcel)
end
local parcel = Parcel.new("sample")
parcel.weight = 4
print(parcel.label .. " " .. tostring(parcel.colour))

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Badge {std::string name;std::string label()const{return "@"+name;}};
int main(){
Badge b{"Ada"};std::cout<<b.label()<<"\n";
}

Trace each program independently. These examples demonstrate the concept with different operations or data from the task; source and target output are not assumed to match.

challenge icon

Challenge

Easy

Input: integer width and height, both nonnegative. Rectangle stores its own dimensions and area returns their product. Driver constructs two independent objects in its probes.

Editable modules: Rectangle.cpp, Rectangle.hpp. Each required type has its own named header and implementation. Preserve all public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#include "Rectangle.hpp"
#include <iostream>
int main(){
{Rectangle a(2,3),b(4,5);if(a.area()!=6||b.area()!=20||a.area()!=6)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int w,h;in>>w>>h;Rectangle r(w,h);std::cout<<r.area()<<"\n";
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C++ for Lua Developers

Practice on your own: Online C++ compiler