Lecture Notes for Introduction to Computer Science II
5 June 2001 - Classes
- classes are just like structs
- classes group related data
- syntax - replace
struct
with class
- data in classes are called members, instance variables
- member types can be anything
- functions are called methods, member functions
- all member names within the same class must be different
- a class may have any number of members, including 0
- declaring members
- a class is like any other datatype - variable declarations, function
declarations
- accessing members - the dot operator
- a members must be accessed through a class instance
- using classes
- classes may be passed around like any other variable
- the class definition must appear in the same file as member accesses
what's the difference
- it's good to delay decisions
- but, decisions need to be made
- make a dumb but immediate decsion and fix it later
- but, what happens when others latch onto your dumb decisions?
access control can solve this problem
- give selective access to struct and class members
- usually the functions, not the data
- public members can be accessed outside the class
- private members can only be accessed from inside the class
more syntax
-
public:
and private:
keywords start public and private member
declarations
- between member declarations, not in them
- may be repeated as many times as desired
- declare before use is suspended for members
- the default access for classes is private; for structs it's public
This page last modified on 6 June 2001.