A method is a type of function that is tied to a [[Class]]. ### Instance Methods An instance method is a method that acts upon a *value* of our class type $T$. ```cpp class Foo { public: int data; explicit Foo(int data) : data(data) {} void print_data() { // in this context (inside a instance method), // we have acces to the 'this' keyword. std::cout << this->data << std::endl; } } ``` >[!seealso] Seealso: [[Constructor]] There is a lot more that can be said about this keyword, but in simple terms, the [[“This”]] keyword is a special variable that points to the *value* / *instance* of the class that the method is being act upon. ```cpp Foo bar = Foo(); foo.print_data(); // when print_data is being run, 'this' is a pointer to 'bar', this == &bar. ``` This pattern of specific methods acting on a instance of some type $T$ shows up a lot in C as well, but the benefit we have of turning this into a method of a [[Class]] is that now these two concepts are fully linked together on a language level: `print_data()` *is part of* the class `Foo`, and *applies to* a value of type `Foo` (which is why `print_data()`’s full qualifier would be `Foo::print_data()`. Allowing us to do this also gives us the power that the [[Invariant|Invariants]] of the [[“This”]] keyword gives us, which allows us to clean these functions with [[Null]] tests or [[Assertions]]. >[!example] CString Example (Full Example [[CString|Here]]) An easy example of this would be turning a struct in C to [[C++]]: > >*C Variant*: >```c >struct CString { > char* contents; > size_t length; >}; > >// ... > >bool contains(const CString* string, char c) { > for (size_t i = 0; i < string->length; i++) { > if (string->contents[i] == c) return true; > } > return false; >} >``` > >*[[C++]] Variant*: >```cpp >class CString { > char* contents; > std::size_t length; > > // ... constructors, destructors, etc > > bool contains(char c) { > for (std::size_t i = 0; i < this->length; i++) { > if (this->contents[i] == c) return true; > } > return false; > } >} >``` > The class version functions very similarly to the C example, however there is one important difference: the C definition targets a $\textbf{const } \text{CString}*$, while our current method acts on a non-const $\text{CString}*$. To fix this issue, see [[Const##Methods]] #### Override In derived classes, it is possible to override functionality of a [[../../99 Old/CS-230/Inheritance|base class through]] [[Polymorphism]]